Understanding Cocoa Memory

What is the advantage of this:

NSArray *array = [[NSArray alloc] initWithObjects:@"Year", "@Capital", ..., nil];
self.hintArray = array;
[array release];

Instead of directly assigning my class variable as follows:

self.hintArray = [[NSArray alloc] initWithObjects:@"Year", "@Capital", ..., nil];

Why do we create a temporary local object and then free it, and not just assign it to our class variable?

+3
source share
3 answers

You could, but you must remember to release it once before moving on. Assignment self.hintArray(assuming that it is a synthesized setter that is stored on the set) will remove keepCount:

NSArray *array = [[NSArray alloc] initWithObjects:...]; // retainCount is 1
self.hintArray = array; // retainCount is 2
[array release]; // retainCount is 1

and

self.hintArray = [[NSArray alloc] initWithObjects:...]; // retainCount is 2:
                                                        // one for the alloc
                                                        // and one for the assign
[self.hintArray release]; // retainCount is 1
+4
source

Others have already noted memory issues, but here is the best way to do this in one step:

self.hintArray = [NSArray arrayWithObjects:@"Year", "@Capital", ..., nil];

+arrayWithObjects , , . . (, , hintArray retain copy).

+7

Since the reference to creating an array in Objective-C's counted memory management scheme will increase the reference count, and if you do not store the return value in a variable, you can send a release message, then there will be no way to reduce that counting and lead to a memory leak.

0
source

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


All Articles