views:

81

answers:

3

Hi,

I've seen in (Apple) sample code two types of ways of allocation memory, and am not sure I understand the difference and resulting behavior.

// FAILS
NSMutableArray *anArray = [NSMutableArray array];
[anArray release];

// WORKS
NSMutableArray *anArray1 = [[NSMutableArray alloc] init];
[anArray release];

By "FAILS" I mean I get crashes/runtime warnings etc., and not always as soon as I call the release...

Any explanation appreciated.

Thanks

+2  A: 

In the first instance you are getting an autoreleased object, which you don't need to release

The second instance is where you are manually allocating the memory yourself, so you a responsible for releasing it.

Read this documentation for help:-

http://developer.apple.com/mac/library/documentation/cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html

djhworld
Just posting to say that you *absolutely* need to read Apple's Objective-C memory management guide. Although that link is slightly incorrect; the real link is http://developer.apple.com/mac/library/documentation/cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html. There is no excuse for programming in Objective-C without reading this guide.
dancavallaro
Whoops, fixed the link. Thanks
djhworld
+1  A: 

To clarify on djhworlds response:

alloc, copy, mutableCopy and new make you the owner of the new object, retain makes you an owner of an existing object, and you become responsible for -[(auto)release]ing it. Other methods return an object that has been -[autoreleased], and thus you don't have any responsibility for it, but beware: It will disappear on the next iteration of the run loop (usually), as that is generally when the autorelease pool drains.

The practical upshot of this is that the //FAILS version works perfectly in the context of that particular piece of code, but once the run loop rolls around and the pool is drained, your object, being already released and gone, causes things to go boom.

Williham Totland
Don't forget retain.
Ty
`-[retain]`! Never forget!
Williham Totland
+5  A: 

Please keep in mind that

NSMutableArray *anArray = [NSMutableArray array];

acts like:

NSMutableArray *anArray1 = [[[NSMutableArray alloc] init] autorelease];

So doing a release again will cause the crash as you are trying to release an autoreleased object.

Hope this helps you.

Thanks,

Madhup

Madhup