If I want to declare a simple button, do I have to do both of the following things?
Inside @interface:
UIButton *button;
and
@property (nonatomic, retain) IBOutlet UIButton *button;
Is the property declaration suffi开发者_StackOverflowcient, or are both needed? If so, why?
The first part, in the @interface, is an ivar declaration. You no longer need to do this if you're declaring a property. In fact, it's a good idea to stop doing this, because it's a private implementation detail that you're exposing in your header.
The second part is a property declaration. This is all you really need. However, if you declare the property, you also need to synthesize the accessors. In your .m file, at the top of your @implementation
block, just stick
@synthesize button;
The @synthesize
tells the property what ivar to use for its backing store. And on modern runtimes (which is iOS and 64-bit OS X) it will also synthesize the ivar for you. So I guess if you're writing 32-bit OS X code, you still need the ivar declaration, but that's the only time.
Apple guys has removed such redundancy by adding a feature (non-fragile abi blablabla) to clang. You can write @property and @synthesize, without ivars inside @interface ClassName{}.
精彩评论