In cocoa2.0 does @property obviate variable declaration in the interface
Just experimenting with @property and @synthesize:
@interface Greeter : NSObject
//{
// NSString * name;
//}
@property (assign) NSString * name;
- (NSString *) greeting;
@end
It seems to 开发者_JAVA技巧be the case that if you declare a variable using @property that you don't have to declare it between the braces (and you don't even need the braces if all of your interface variables are all declared using @property). Is this always correct? And is it good style to leave out the top part of the interface (braces included)? I have been using both and been irritated by the redundancy.
There is no “Cocoa 2.0”.
In Objective-C 2.0, on the modern runtime, yes, you can leave out the instance variables, and the property will generate them for you. The legacy runtime on Mac OS X still requires explicit instance variables.
You cannot leave out the ivar section entirely yet, but you can leave it empty.
Here is the webpage where I first found out you can automatically have you properties synthesized and also declare new properties in class extensions. It gives a bit of interesting back story as well.
http://www.mcubedsw.com/blog/index.php/site/comments/new_objective-c_features/
As for style and correctness, I've been using primarily properties for the last couple of weeks and it has made my code look quite clean! I can now declare private properties in my implementation and not have them exposed in the header making any interface to use my classes very simple and non-confusing to use.
I've ran into a problem when using interface builder where having an iVar to any subviews of a view controller still has to be declared in the header for interface builder to see it as an IBOutlet and assign to it. You can still declare those @private though and then have the private properties declared in a class extension in your implementation if you really want it as a property for you to use.
// In your header
@interface MenuViewController : UIViewController {
@private
IBOutlet UIButton *buttonPeopleShouldNotKnowAbout;
}
@end
// And in your implementation
@implementation MenuViewController ()
@property (nonatomic, readwrite, assign) IBOutlet UIButton *buttonPeopleShouldNotKnowAbout;
@end
精彩评论