Reputation: 345
This is my code using NSMutableArray.
- (void) put:(NSString *)key value:(NSString *)value
{
Element *element = [[[Element alloc] initWith:key strValue:value] autorelease];
if (self.map) {
[map addObject:element];
}
else {
map = [NSMutableArray arrayWithObject:element];
}
}
-(void)dealloc
{
if (map) {
[map release];
}
[super dealloc];
}
My apple crashes at line:[map release];
What's wrong in my code?
I tried releasing 'map' as follow.
- (void) put:(NSString *)key value:(NSString *)value
{
Element *element = [[[Element alloc] initWith:key strValue:value] autorelease];
if (self.map) {
[map addObject:element];
}
else {
map = [NSMutableArray arrayWithObject:element];
[map release]
}
}
Then the apple does not crash. How solve this problem?
Upvotes: 0
Views: 224
Reputation: 1637
You are using the convenience initializer arrayWithObject
, which has an implicit autorelease
. You can't release
an autoreleased object.
Upvotes: 0
Reputation: 7148
The arrayWithObject:
method returns an autoreleased object; you need to either retain the array:
map = [[NSMutableArray arrayWithObject:element] retain];
or use the initWithObject:
method:
map = [[NSMutableArray alloc] initWithObject:element];
Upvotes: 3
Reputation: 6139
If map is a retained/copied property do self.map=...
to retain it. [NSMutableArray arrayWithObject:element]
returns an autoreleased object that needs to be retained.
Upvotes: 1