问题描述
由于引用计数变为0,将导致对象被释放.我很好奇一个弱对象什么时候释放,因为计数总是为0,当我声明一个弱对象时,我是否需要担心它会中途释放?
Since the reference count becoming 0 will cause the object being released.I am curious when is a weak object released since the count is always 0, when I declare a weak one, do I need to worry about it will be released half way?
例如
NSObject ClassA
@property (weak) NSString stringA;
- init() {
...
stringA = @"this is a weak string";
...
}
- doSomething() {
// When I call this function later,
// is there any chance at this point stringA has been released?
NSLog(stringA);
}
推荐答案
如果通过IBOutlet
或a作为delegate
/datasource
连接,则只能声明弱属性. >(引用另一个UIViewController
).
You would only declare a weak property if it was connected via an IBOutlet
or a as a delegate
/datasource
(references another UIViewController
).
如果您创建一个弱属性,它将在实例化后立即释放.但是,通过IBOutlet
连接的weak
属性将不会释放,因为视图牢固地持有该属性.
If you make a weak property, it will be released immediately after instantiating it. However, a weak
property connected via an IBOutlet
will not release because the view holds strongly to the property.
与VC类型的属性(例如delegate
)相同,它们是weak
属性,因为您将类分配给该属性.显然,VC是强势持有的,因此代表应避免强力持有VC,以防止保留周期(其中a
强烈持有b
而b
强烈持有a
).
Same with properties of type VCs, such as delegate
s, they are weak
properties because you assign your class to the property. The VC is obviously held strongly so the delegate should refrain from holding strongly to the VC to prevent retain cycles (where a
holds strongly to b
and b
holds strongly to a
).
因此,要回答您的问题,如果没有任何强力支持,则会立即释放weak
属性,以上是使用weak
属性的情况.
So to answer your question, a weak
property will be released immediately if nothing holds strongly to it, and the above is scenarios where you will use a weak
property.
这篇关于在目标C中,何时在ARC下释放弱对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!