Wednesday, April 6, 2011

initializing a class. Can you see any problems with this?

-(id)init {

if (self = [super init]) {

 self.name = [[NSString alloc] init];
 self.type = [[NSString alloc] init];
 self.phoneNumber = [[NSString alloc]init];
 self.webAddress = [[NSString alloc] init];

 NSMutableArray *pricesArray = [[NSMutableArray alloc] init];
 NSMutableArray *poolsArray = [[NSMutableArray alloc] init];
 self.prices = pricesArray;
 self.pools = poolsArray;

 [pricesArray release];
 [poolsArray release];

 //Create the address dictionaries



 NSMutableDictionary *addressItems = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"", KAddressStreet1Key, @"", KAddressStreet2Key, @"", KAddressBoroughKey, @"", KAddressCityKey, @"", KAddressCountyKey, @"", KAddressPostCodeKey, @"" ,KAddressCountryKey, nil];

 //Add dictionary to the array to contain address values

 self.address = addressItems;

 [addressItems release];

}

return self;

}

I'm currently doing a massive round of debugging thanks to EXC_BAD_ACCESS errors.. grr.

Does the code above seem fine and logical for a class init method? Basically I'm getting the EXC_BAD_ACCESS errors when I release both the pools mutable array and the dictionary...

Dan

From stackoverflow
  • How are your properties declared? If they are not declared with retain then most of your objects will be deallocated at the end of this method.

    Dan Morgan : Ah yes apologies. collections are 'retain' and strings are 'copy'
  • You're leaking objects with each allocation for the string properties. Other than that, I don't notice anything wrong. How are the AddressXKeys defined?

    Dan Morgan : Ah ok thanks Barry. So the alloc is +1 and the copy property is also +1 to my retain count? Address Keys are like this: #define KAddressStreet1Key @"1address"
    Barry Wark : Yes, the copy property makes a copy of the string and keeps a reference to the copy, so the original is lost but has a retain count of +1. copy properties should be treated like retain properties for memory management purposes.
    Barry Wark : Freebie hint: the Cocoa pattern for string constants like this is to define a global string reference. This way you can compare pointers rather than using -[NSString isEqual:]. See http://stackoverflow.com/questions/538996/constants-in-objective-c/539191#539191

0 comments:

Post a Comment