I have a question about how instance variables work and when to use the @property. Here is an example interface file I am working with
@interface PackageModel : NSObject {
NSString *tracking;
NSString *carrier;
NSString *status;
NSMutableDictionary *events;
// Connection ivars
NSMutableData *receivedData;
// Parsing ivars
int tagLevel;
NSMutableArray *tagTree;
NSString *parentTag;
NSString *currentTag;
}
@property (nonatomic, retain) NSMutableData *receivedData;
- (id)initWithTrackingString:(NSString *)string;
- (void)getPackageDataWithEvents;
- (void)printMe;
@end
How can I access these in the file’s code. Can I access tracking, carrier, and status in this class’s methods just by using something like
tracking = [[NSString alloc] initWithString:@"Hello World"];
Also, what variables need to be put in the dealloc? Only the variables I have in the @property/@synthesize? Or do I need to release all the instance variables in the dealloc method.
I am just looking for some clarification on how instance variables work in Objective-C. Thanks.
@propertydeclarations are nothing more than compiler-generated getter and setter methods. That’s it. Just the methods. Obviously, you have to be getting and setting something, so we create the ivar that goes along with the getters and setters. In your example above, your compiler is generating:The getter returns the value in the
receivedDatainstance variable, and the setter changes the value in thereceivedDatainstance variable.(Side note: with the 64-bit runtime, you can skip declaring the instance variable, but I still like to put it in just to be explicit)
As for what you should do in your
deallocmethod, you need to release the instance variables that have beenretained orcopyed. So in your example, you’ll need to do[receivedData release];in yourdeallocmethod, because when you set thereceivedDataivar, you retained the new value (that’s what theretainmeans on the@propertyline). If you don’t specify eitherretainorcopyin the@propertydeclaration, then it defaults toassign, and you don’t have to do anything. Beyond this, you’ll need to release any other instance variables that you retained yourself (ie, not through an@property (retain)setter).For your last question, yes you can just do:
Inside your own class, you have direct access to all your own instance variables (and any protected and public ivars of your super classes).