在ARC下,如何释放NSArray中的元素?

时间:2021-04-22 14:21:43

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

在标准的Objective-C手动内存管理下,在这个问题中建议使用初始化NSArray的方法

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?

鉴于我们不再可以在自动引用计数下使用-release,在ARC下发布此NSArray的建议方法是什么?

2 个解决方案

#1


12  

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:

如果imageArray是对象的ivar(可能不是一个安全的假设),你应该使用一个访问器将数组设置为nil;访问器将负责释放阵列及其所有成员:

[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:

如果您需要清理一个包含许多成员的数组,但在该ivar中保留一个有效的数组,以便其他方法可以安全地向其发送消息,则可以使用以下命令:

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

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

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

这将用一个新的空数组替换旧数组。

#2


19  

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

要使用ARC,您只需删除保留和释放消息即可。所以你摆脱了这样的数组:

 imageArray = nil;

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

这有效并且不会泄漏,因为在ARC下,编译器会自动插入必要的保留和释放调用。

#1


12  

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:

如果imageArray是对象的ivar(可能不是一个安全的假设),你应该使用一个访问器将数组设置为nil;访问器将负责释放阵列及其所有成员:

[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:

如果您需要清理一个包含许多成员的数组,但在该ivar中保留一个有效的数组,以便其他方法可以安全地向其发送消息,则可以使用以下命令:

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

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

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

这将用一个新的空数组替换旧数组。

#2


19  

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

要使用ARC,您只需删除保留和释放消息即可。所以你摆脱了这样的数组:

 imageArray = nil;

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

这有效并且不会泄漏,因为在ARC下,编译器会自动插入必要的保留和释放调用。