cromestant
cromestant

Reputation: 660

Objective-C memory management: if I release a string stored in an array, it only releases this reference or it releases the object in the array?

If I have this:

NSString *lastPushed = (NSString *)[tagStack objectAtIndex:[tagStack count]-1];
.//do something with the last pushed element locally
.//do more cstuff here
.//after doing all the stuff needed in the function

[lastPushed release];

where tagStack is an NSMutableArray

If I release lastPushed, since it was not copied, or inited, will it only release this reference or will it actually release the object in the mutableArray?

Upvotes: 0

Views: 68

Answers (3)

Abizern
Abizern

Reputation: 150665

You didn't alloc, new, or copy or mutableCopy lastPushed, so why are you releasing it?

Since lastPushed is a pointer to the object in the array, you are releasing that. This could lead to a problem when your array thinks that it has a valid pointer to an object but you've released it and it's been dealloced.

Upvotes: 5

John Parker
John Parker

Reputation: 54445

You shouldn't be releasing lastPushed, as you didn't use alloc, copy or new. (It's that simple.)

If you want to remove it from the mutable array, you should use the appropriate method in the NSMutableArray (removeObject or removeObjectAtIndex, etc.) Otherwise, it's unclear what you're trying to do which will bite you next week/month/year, etc.

Upvotes: 2

Ole Begemann
Ole Begemann

Reputation: 135558

It will release the object in the array because both lastPushed and the array point to the same object.

As always, you should follow the management rules. Do not release anything that you have not created, retained or copied.

Upvotes: 4

Related Questions