Who is responsible for freeing objects in the array when copying?

In Objective-C, if array1 is copied to array2 using mutableCopy, and suppose the code is executed in main (), who is responsible for freeing the objects contained in the array? Is it main () or array2?

+3
source share
4 answers

I think the previous answers missed this point, or the seeker was rather obscure. The actual question is not in any array, but in the contents of the array:

who is responsible for freeing the objects contained in the array ? Is it main () or array2?

array1 array2 .

NSArray:

" - , , , , ."

, NSArray array1. array2 -mutableCopy, NSMutableArray, , . array1 , dealloc , . , array2 , - 0, , array2 , ( array2).

(, , ..) , , , . -mutableCopy, , array2, , .

+13

Obj-C. , :

, .. . ( , , ). , , .

+1

. :

int main(int argc, char *argv[])
{
    // ...

    NSObject *obj1 = [[NSObject alloc] init]; // owned
    NSObject *obj2 = [[NSObject alloc] init]; // owned
    NSObject *obj3 = [[[NSObject alloc] init] autorelease]; // not owned

    NSMutableArray *array1 = [NSMutableArray arrayWithObjects: obj1, obj2, obj3, nil]; // not owned
    NSMutableArray *array2 = [array1 mutableCopy]; // owned

    // ...

    [array2 release];
    [obj2 release];
    [obj1 release];

    // ...
}

obj1 obj2, , obj3, . arrayWithObjects:, , mutableCopy, . , , - , , .

, obj1, obj2 obj3 , , NSArray, doesn ' , .

Cocoa , .

+1

. main() .

However, in my experience, freeing objects causes applications to crash. ObjC does a good job with automatic memory management. My Cocoa apps never seem to need more memory than they started, even after a few hours.

-5
source

Source: https://habr.com/ru/post/1711921/


All Articles