Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare properties in .h interface or in an extension in .m file?

In Objective-C, is it best practice to:

  1. Declare objects such as buttons in the .h and then synthesize in the .m

    .h
    @interface SomeViewController : UIViewController  
      @property (strong, nonatomic) UIButton *someButton;  
    @end
    
    .m
    @implementation SomeViewController  
      @synthesize someButton = _someButton;  
    @end
    
  2. or declare them as ivars in the .m

    @interface SomeViewController ()  
      @property (strong, nonatomic) UIButton *someButton;  
    @end  
    

I notice that in a lot of Apple code, specifically their Breadcrumbs sample code, many of their properties are declared in the interface. Is there a difference between the two? I also noticed that when properties are declared in the @interface, they are automatically synthesized with an underscore prefix, making the someButton = _someButton synthesis useless.

like image 242
HighFlyingFantasy Avatar asked Jan 03 '13 02:01

HighFlyingFantasy


1 Answers

First, as of Xcode 4.4 there is no longer a need to @synthesize(unless you change both the setter and getter method), either when the @property is declared in the @interface or @implementation.

If the @property is only accessed from within the class then declare the @property in a class extension in the .m file. This provides encapsulation and make it easy to see that the @property is not used from another class.

If the @property is used by other classes, by design, then define it in the @interface in the .h file.

like image 150
zaph Avatar answered Oct 29 '22 23:10

zaph