Cocoa Memory Management NSArray with Objects

前端 未结 2 915
Happy的楠姐
Happy的楠姐 2021-01-26 01:58

I\'m having troubles releasing objects.. To explain it better I have included my code below.

NSTask *task = [NSTask new];
NSTask *grep = [NSTask new]; 
NSPipe *p         


        
相关标签:
2条回答
  • 2021-01-26 02:38

    substringToIndex: returns an autoreleased string, so there's no need to release it.

    The only memory leak I see is where you set up your 'pipe' var a second time (for the task's standard output) without first releasing its current value (the NSPipe instance used for standard error & input).

    Mutable collections like NSMutableArray will retain the objects they contain (as do all mutable/nonmutable collections) then release them when they're removed (or when the collection itself is deallocated).

    0 讨论(0)
  • 2021-01-26 02:57

    Memory management in Objective-C has one fundamental rule:

    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.

    Thus every call to new in your code sample should be balanced with a call to release or autorelease. The NSArray, along with most other objects in the code, isn't created with either, so it doesn't need to be released. The [NSString alloc] is autoreleased, so it's taken care of. Collections manage their own items, retaining and releasing them as necessary: when an item is inserted, it's retained; when it's removed, it's released. Dictionary keys are copied rather than retained.

    Where you've got an unbalanced new (and hence leak) is the first NSPipe you created. Release it before creating the pipe for grep's standard output. Perhaps you simply left it out of the sample, but you're also not setting any arguments for the grep task.

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