Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Under ARC, how do I release the elements in an NSArray?

Under standard Objective-C manual memory management, it was suggested in this question that the way to release an NSArray initialized using

imageArray  = [[NSArray alloc] initWithObjects:[UIImage imageNamed:@"1.png"], 
                        [UIImage imageNamed:@"2.png"],
                        nil];

was to use

[imageArray release];
imageArray = nil;

Given that we no longer can use -release under automatic reference counting, what would be the suggested way to release this NSArray under ARC?

like image 870
Lucas Avatar asked Aug 26 '11 13:08

Lucas


2 Answers

To use ARC you just remove your retain and release messages and that's it. So you get rid of your array like this:

 imageArray = nil;

This works and doesn't leak because under ARC the compiler automatically inserts the necessary retain and release calls.

like image 162
Sven Avatar answered Nov 26 '22 16:11

Sven


If the imageArray is an ivar for an object (perhaps not a safe assumption), you should use an accessor to set the array to nil; the accessor will take care of releasing the array and all of its members:

[self setImageArray:nil];

If you need to clean out an array with many members but keep a valid array ready in that ivar so that other methods can safely send it messages, you can use the following:

[self setImageArray:[[NSArray alloc] init]];

Which will replace the old array with a new, empty array.

like image 35
matthias Avatar answered Nov 26 '22 15:11

matthias