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?
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.
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.
精彩评论