Initiate an object, and then store it in an NSArray. Will it be a leak?

If the object in my view is left to me, so I store it and I store it in NSArray, which stores what is stored in it, can I rely on NSArray to see that it is already saved and does not increase the score Or do I need to run through the array and decrease the hold counter so that there is no memory leak?

+3
source share
5 answers

To exclude ownership of an object added to NSArray, send a message -releaseto the object immediately after adding it to NSArray. If you do not, you will indeed have a memory leak.

Here's what happens:

NSString *str = [[NSString alloc] initWithFormat:@"%@", @"Blah"]; //retain count is 1, you own this object
[array addObject:str]; //retain count gets bumped to 2
[str release]; //retain count is 1 - relinquishing ownership here.
//There is no leak because when the NSArray is
//deallocated, the object will be sent the release message.

-release, NSArray , 1, , , , .

+4

, . . . , . . .

+6

, NSArray, , .

, , , NSArray ( , ) , , .

, " objective-c ", .

+2

. NSArray , . , . , , .

+1

NSArray will save your object when you add it, and then release it when you remove it from the array. This is by design. This means that to prevent memory leaks, if you already saved the object before adding it to the array, you should free it after deleting it from the array:

NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:10];
NSObject *object = [[NSObject alloc] init]; // retain count of 1 (because of alloc)
[object retain]; // useless, just for example, retain count of 2 (because of retain)
[array addObject:object]; // array is mutable, retain count of 3 (because of addObject:)
[array removeObject:object]; // retain count of 2
[object release]; // retain count of 1
[object release]; // retain count of 0, the object is dealloc'd afterwards
[array release]; // to be sure that we are not leaking an array, too
0
source

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


All Articles