Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C properties, how do they work?


Assume we have a class Foo with a property bar.
Declared like this in the header:

@interface Foo : NSObject {
    int bar;
}

@property (nonatomic, assign) int bar;

@end

In the .m I have @synthesize bar; of course.

Now, my question is, if I remove the int bar; line, the property behaves the same way, so, is that line really necessary? Am I missing some fundamental concept?

Thanks!

like image 554
Santiago V. Avatar asked Dec 08 '25 06:12

Santiago V.


1 Answers

The "modern" Objective-C runtime generates ivars automatically if they don't already exist when it encounters@synthesize.

Advantages to skipping them:

  • Less duplication in your code. And the @property gives the type, name and use (a property!) of the ivar, so you're not losing anything.
  • Even without explicitly declaring the ivar, you can still access the ivar directly. (One old release of Xcode has a bug that prevents this, but you won't be using that version.)

There are a few caveats:

  • This is not supported with the "old" runtime, on 32-bit Mac OS X. (It is supported by recent versions of the iOS simulator.)
  • Xcode may not show autogenerated ivars in the debugger. (I believe this is a bug.)

Because of the debugger issue, at the moment I explicitly add all my ivars and flag them like this:

@interface Foo : NSObject {
    #ifndef SYNTHESIZED_IVARS
    int ivar;
    #endif
}

@property (nonatomic, assign) int bar;

@end

My plan is to remove that block when I've confirmed the debugger is able to show the ivars. (For all I know, this has already happened.)

like image 149
Steven Fisher Avatar answered Dec 09 '25 19:12

Steven Fisher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!