Search code examples
iosobjective-ciboutlet

IBOutlet declaration place


After searching on Google about this confusion, I found out that the best place to put an IBOutlet is:

@interface GallantViewController : UIViewController

@property (nonatomic, weak) IBOutlet UISwitch *switch;

@end

but from what I say, now the switch variable is visible outside of the GallantViewController. Isn't that odd? I thought that this wrong method:

@interface GoofusViewController : UIViewController {
    IBOutlet UISwitch *_switch
}

@end

was behaving like this, and moving it would fix it. Why would you want to manipulate a button for example from another class instead of implementing it's logic just in the GallantViewController?


Solution

  • The @interface can appear in both the .h file (public properties) and the .m file (private properties). The IBOutlets should be declared in the .m file.

    For example, here's a sample .m file for a view controller

    #import "MainViewController.h"
    
    @interface MainViewController ()
    // the following property is not visible outside this file
    @property (weak, nonatomic) IBOutlet UIView *someView;  
    @end
    
    @implementation MainViewController
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
    }
    
    @end
    

    Technically, the @interface in the .m file is a class extension (also known as an anonymous category on the class), but that's of no practical interest. It's just a way to add private properties to the class.