Sunday, July 17, 2011

How to assign initial values to variables in your init methods with proper memory management

A simple but important technique learned from Chapter 15 of the book "Learn Objective-C on the Mac", which I think is quite important when you are assigning initial values to variables in your init methods.



@implementation Thingie 
@synthesize name; 
@synthesize magicNumber; 
@synthesize shoeSize; 
@synthesize subThingies;

- (id)initWithName: (NSString *) n 
       magicNumber: (int) mn
          shoeSize: (float) ss {
    
    if (self = [super init]) {
        self.name = n; 
        self.magicNumber = mn; 
        self.shoeSize = ss; 
        self.subThingies = [NSMutableArray array];
    } 
    return (self);
}

"Notice that in the init method we’re using self.attribute on the left-hand side of the assignments. Remember that this actually means that we’re calling the accessor methods for those attributes, and these methods were created by @synthesize. We’re not doing a direct instance variable assignment. This object creation technique will get us proper memory management for the passed in NSString and for the NSMutableArray we create, so we don’t have to provide it explicitly."


0 comments:

Post a Comment