Search code examples
objective-cxcodeibactioniboutlet

Where should I put IBOutlets and IBActions?


Here's some example code to explain myself:

MyViewController.h

@interface MyViewController
@property (nonatomic, strong) IBOutlet UIButton *button1;
  - (IBAction)button1Touch;
@end

MyViewController.m

@interface MyViewController ()
@property (nonatomic, strong) IBOutlet UIButton *button2;
- (IBAction)button2Touch;
@end

@implementation MyViewController {
  IBOutlet UIButton *button3;
}

- (IBAction)button1Touch {
}

- (IBAction)button2Touch {
}

- (IBAction)button3Touch {
}

@end

When I learned how to use XCode, all tutorials used button1/button1Touch approach. Recently I've encountered button2/button2Touch approach in one project. So I tried button3/button3Touch variation and it works fine as well.

For me button1/button1Touch is (generally) a bad approach, because it's internal property and method and shouldn't be used by someone who'll use MyViewController or extend it. Of course if it's used outside of MyViewController, then it's fine to declare it here, but usually I'm trying to hide everything I don't need to show.

So button2/button2Touch and button3/button3Touch are better approaches, but I don't really see difference between them. And if I don't see the difference, then I would use button3/button3Touch approach, because it doesn't need anonymous extension and simpler overall.

So that's my reasoning. But is it correct one or there are other reasons why I would use #1/#2 approaches?


Solution

  • The 2nd approach allows you to use @property (which is not possible in the 3rd approach as you already found out I guess, since the compiler complains).

    It is more common (and cleaner, in my opinion) to declare all your private properties and methods in the class extension (what you refer to as "anonymous extension").

    I'm also curious if there are more serious caveats by using your 3rd approach - if someone knows please share.