Lars Petersen
Lars Petersen

Reputation: 622

Can I release an object which was added to a NSMutableArray or does this affect a crash?

I've got one question about the memory management of the NSMutableArray. I create an object of my custom class and add this object to a NSMutableArray. Is this automatically retained, so that I can release my created object?

Thanks!

Upvotes: 1

Views: 110

Answers (2)

cutsoy
cutsoy

Reputation: 10251

Yes, you can do this for example:

NSMutableArray *array = [[NSMutableArray alloc] init];
NSString *someString = @"Abc";
[array addObject:someString];
[someString release];
NSLog(@"Somestring: %@", [array objectAtIndex:0]);

Upvotes: 1

Philippe Leybaert
Philippe Leybaert

Reputation: 171734

Yes, it is automatically retained. You should release your object after adding it to the array (or use autorelease)

For example:

NSMutableArray *array = [[NSMutableArray alloc] init];

[array addObject:[[[MyClass alloc] init] autorelease]];

// or

MyClass * obj = [[MyClass alloc] init];

[array addObject:obj];

[obj release];

Upvotes: 4

Related Questions