Objective C release, autorelease, and data types

后端 未结 3 510
轻奢々
轻奢々 2020-12-07 18:17

I\'m new to memory managed code but I get the idea pretty well.

On taking my app through the leaks tool in XCode, I noticed I only had to clean up my custom objects,

3条回答
  •  长情又很酷
    2020-12-07 18:40

    Cocoa uses certain naming conventions. Anything that starts with alloc, new, or copy returns something with a retainCount of 1 and you are required to release. Anything else that a function returns has a balanced retainCount (it might be held by something else, or it might be retained and out released).

    So:

    NSMutableArray *removals = [NSMutableArray new];
    

    Has a retainCount of 1, and:

    NSMutableArray *removals = [NSMutableArray arrayWithCapacity:99];
    

    or

    NSMutableArray *removals = [NSMutableArray array];
    

    Don't since the methods are not prefixed with alloc, new or copy. This is all spelled out in the memory management documentation. In particular:

    You take ownership of an object if you create it using a method whose name begins with “alloc” or “new” or contains “copy” (for example, alloc, newObject, or mutableCopy), or if you send it a retain message. You are responsible for relinquishing ownership of objects you own using release or autorelease. Any other time you receive an object, you must not release it.

提交回复
热议问题