In Objective C you can now use @property and @synthesize to auto generate get and set methods. My question is: Do I still need to declare the property in the interface? My program compiles and runs fine without it. But most books and other examples still have it. Why?
@interface Person : NSObject {
// do i need the declaration "NSString name;"? why?
// i have notice that my program works fine without it.
// but many programming examples still incude it.
// NSString name;
}
@property NSString *name;
@end
@implementation Person
@synthesize name;
@end
This depends on runtime. Modern runtime is used in iOS and you don't have to declade ivars. This is not always the case in OS X though. See here - http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtVersionsPlatforms.html
What you're talking about is the ivar. You do not need to declare it as the @synthesize adds it for you. This did not use to be the case on older compilers (and obviously before @propertiy was added to the language), thus a lot of people and books still do.
PS: You also do not need the {...} if you don't have any ivars, e.g.:
@interface Person : NSObject
@property NSString *name;
//...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With