iPhone memory management, a newbie question

前端 未结 3 1510
夕颜
夕颜 2021-01-07 02:51

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
NSMuta         


        
相关标签:
3条回答
  • 2021-01-07 03:04

    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.

    0 讨论(0)
  • 2021-01-07 03:06

    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

    0 讨论(0)
  • 2021-01-07 03:09

    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

    0 讨论(0)
提交回复
热议问题