Question

I understand that @synthesize autocreates the getters and setters for an instance variable. When I specify the = _something part, I understand that this informs the compiler/runtime that I want it to use a particular backing variable for the getters/setters.

Does Objective-C autocreate the _something variable along with my getters/setters or should I be defining that instance variable in my interface/implementation file?

Was it helpful?

Solution

The question is whether @property in the header file and @synthesize in the implementation creates the underlying ivar or whether the ivar has to listed in the header file. Example, in the header file:

@interface SomeClass : NSObject {
    NSString *_someString;    // Is this needed???
}
@property NSString *someString;

and in the implementation:

@synthesize someString = _someString;

The answer is that it depends on whether or not you are using the legacy or modern runtime. In iOS you are always using the modern runtime so you never need the NSString *_somestring line, but this question is about Mac OS X. For Mac OS X if you are using a 64-bit program on Mac OS X 10.5 or later you are using the modern runtime, otherwise you are using the legacy runtime and need the extra line in your header file. Since there's been some misinformation posted, here is a reference: Objective-C Runtime Programming Guide.

OTHER TIPS

Sorry, misread a part of your question. If you do the @synthesize part with the underscore, you're all good. No need explicitly define an ivar.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top