In Objective C, When is weak object released under

2019-09-02 09:29发布

问题:

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?

For example

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);
}

回答1:

You would only declare a weak property if it was connected via an IBOutlet or a as a delegate/datasource (references another UIViewController).

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.

Same with properties of type VCs, such as delegates, 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).

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.



回答2:

Strings are a bad example. There are certain objects that get never released. Constant strings, [NSNull null], @YES and @NO, small NSNumber values in 32 bit and many NSNumber values in 64 bit, empty arrays, and so on. Since they are not released, a weak variable will never be nil.

Many objects are autoreleased. If nothing else references them but their autorelease pool, they go away when the pool goes away.

But if you create an object with alloc/init and store it in a weak variable, the compiler knows that alloc/init had a reference count of 1, that reference count is removed, and poof! it goes. If you store the reference into a local variable first which is strong by default, it goes away when the code leaves the scope of the local variable. If you store into a weak variable first and then from the weak variable immediately into a strong one, it is too late, it's gone.