Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I still need to declare the instance variable if I am using @property?

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
like image 475
john.stein Avatar asked Jan 23 '26 10:01

john.stein


2 Answers

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

like image 127
pronvit Avatar answered Jan 26 '26 07:01

pronvit


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;
//...
like image 30
hypercrypt Avatar answered Jan 26 '26 09:01

hypercrypt



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!