13

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.

jscs
  • 63,694
  • 13
  • 151
  • 195
HighFlyingFantasy
  • 3,789
  • 2
  • 26
  • 38
  • 2
    Both of those declarations are property declarations. The ivar is created by the `@synthesize`. They function identically; the difference is their visibility to other files. – jscs Jan 03 '13 at 02:11

1 Answers1

31

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.

mfaani
  • 33,269
  • 19
  • 164
  • 293
zaph
  • 111,848
  • 21
  • 189
  • 228
  • 1
    I'd like to comment that "it's rarely necessary to use `@synthesize`" anymore. (In some instances, such as readonly properties or properties on Core Data subclasses, it is actually still necessary to use `@synthesize` as Xcode still doesn't understand these very well.) – JRG-Developer Jan 03 '13 at 02:45
  • I totally agree with @JRG-Developer. – zaph Jan 03 '13 at 03:08
  • 1
    Here's a detailed discussion: [Automatic Property Synthesis With Xcode 4.4](http://useyourloaf.com/blog/2012/08/01/property-synthesis-with-xcode-4-dot-4.html) – Basil Bourque Nov 30 '13 at 22:39
  • 1
    @Basil I check "Use Your Loaf" every week, great stuff! Thanks for the link. – zaph Nov 30 '13 at 23:11