且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

NSMutableArray销毁

更新时间:2021-08-14 15:50:59

如何创建泄漏的对象?
如果你这样做:

How did you create the objects that are leaking? If you did something like this:

- (void)addObjectsToArray {

    [list addObject:[[MyClass alloc] init];

    OtherClass *anotherObject = [[OtherClass alloc] init];
    [list addObject:anotherObject];
}

那么当list被释放时,你会泄露两个对象。

then you will leak two objects when list is deallocated.

您应该用以下代码替换任何此类代码:

You should replace any such code with:

- (void)addObjectsToArray {

    MyClass *myObject = [[MyClass alloc] init];
    [list addObject:myObject];
    [myObject release];

    OtherClass *anotherObject = [[OtherClass alloc] init];
    [list addObject:anotherObject];
    [anotherObject release];
}

更详细:

如果您遵循第一种模式,则您已创建两个对象,根据您拥有的可可内存管理规则。你有责任放弃所有权。如果你不这样做,对象将永远不会释放,你会看到一个泄漏。

If you follow the first pattern, you've created two objects which, according to the Cocoa memory management rules you own. It's your responsibility to relinquish ownership. If you don't, the object will never be deallocated and you'll see a leak.

你不会立即看到泄漏,因为你通过对象到数组,它也拥有它们的所有权。只有在从数组中删除对象或者当数组本身被释放时,才会识别泄漏。当这些事件发生时,数组放弃对象的所有权,它们将在应用程序中保持活状态,但不会有任何引用。

You don't see a leak immediately, though, because you pass the objects to the array, which also takes ownership of them. The leak will only be recognised when you remove the objects from the array or when the array itself is deallocated. When either of those events occurs, the array relinquishes ownership of the objects and they'll be left "live" in your application, but you won't have any references to them.