在快速枚举期间将对象设置为nil [英] Setting objects to nil during fast enumeration

查看:167
本文介绍了在快速枚举期间将对象设置为nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在通过数组枚举时将对象设置为"nil",如下所示:

I want to set an object to 'nil' as I enumerate through an array, as follows:

for(Object* object in array){
    object = nil;
}

Xcode然后告诉我'默认情况下,不能在ARC中修改快速枚举变量;声明变量__strong允许这样做.'

Xcode then tells me 'Fast enumeration variables can't be modified in ARC by default; declare the variable __strong to allow this.'

这意味着要这样做:

for(Object __strong* object in array){
    object = nil;
}

这似乎是多余的.据我了解,声明对一个对象的强引用会使其保留计数增加一,而对其无效则将保留计数减少一.那么,如何在通过数组枚举时将对象设置为nil?

This seems to be redundant. As far as I understand, declaring a strong reference to an object increases its retain count by one, and nil-ing it decreases the retain count by one. So how, then, do I set an object to nil while enumerating through an array?

我正在使用ARC.

推荐答案

请参见

See Fast enumeration iteration variables in the Clang "Objective-C Automatic Reference Counting" documentation:

如果在Objective-C快速状态下声明了变量 枚举循环,并且变量没有显式所有权 限定符,然后用const __strong和对象限定 枚举过程中遇到的实际上没有保留.

If a variable is declared in the condition of an Objective-C fast enumeration loop, and the variable has no explicit ownership qualifier, then it is qualified with const __strong and objects encountered during the enumeration are not actually retained.

理论上
这是一种优化的可能,因为快速 枚举循环保证在执行过程中保留对象 枚举,并且集合本身不能同步 修改的.可以通过明确限定变量来覆盖它 使用__strong,这将使变量再次可变并导致 循环以保留遇到的对象.

Rationale
This is an optimization made possible because fast enumeration loops promise to keep the objects retained during enumeration, and the collection itself cannot be synchronously modified. It can be overridden by explicitly qualifying the variable with __strong, which will make the variable mutable again and cause the loop to retain the objects it encounters.

因此,默认情况下,循环变量是不可变的,出于性能原因,当前对象的保留计数不会增加.

So by default, the loop variable is immutable, and the retain count of the current object is not increased for performance reasons.

如果将循环变量显式声明为__strong,则它是可变的强引用,并且当前对象的保留计数增加,并且将循环变量设置为nil会再次减少保留计数.但是这样做并不会释放对象或将其从数组中删除,因为数组拥有对该对象的另一个强引用.

If you explicitly declare the loop variable as __strong, it is a mutable strong reference, and the retain count of the current object is increased, and setting the loop variable to nil decreases the retain count again. But doing so does not deallocate the object or remove it from the array, because the array holds another strong reference to the object.

这篇关于在快速枚举期间将对象设置为nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆