2
votes

I'm developing a custom iOS SDK. I'm creating weak, strong references based on my requirement. What is not clear to me is: when will the weakly reference object gets de-allocated?

Assume I have 3 objects A,B,C. A has a weak reference to B and B has strong reference to C.

A --- >(weak ref) B --->(strong ref)C. All the 3 objects are In-memory objects. Since B does not have any strong references to it, it may get de-allocated. Once B is deallocated, C object memory leaks.I cant have strong ref from "c" back to "B" to prevent it from getting de-allocated as it may cause retain cycles. How will ARC takes a decision to de-alloc B? I do understand that objects will be deallocated immediately when the last strong reference to them goes away.But there is no objects strongly refering to "B" at any cause.In this case,When will B gets de-allocated?.

4
When B is deallocated, C also gets deallocated. It doesn't "leak" as you put it. - Rahul Iyer
@John : But my question is ,when will "B" gets de-allocated?. - Karthik207
Catfish_Man's answer is correct. Why don't you just run your code, and try it. - Rahul Iyer

4 Answers

3
votes

Weakly referenced objects will be deallocated immediately when the last strong reference to them goes away. Note that that may not be exactly when your last strong reference goes away, if the object has been retained and autoreleased by ARC (essentially creating an additional temporary strong reference).

3
votes

In your example, since B does not have any strong references to it, it can be deallocated at any time, possibly immediately. When B get deallocated, C does not have any strong references to it which will cause it to be deallocated as well, so it not leak.

It is important to understand that ARC is not garbage collection, in that it doesn't run a process at runtime, collecting the objects that are not needed. It works at compile time, inserting dealloc's in your code when the object no longer pointed at.

1
votes

Xcode gives you a hint about this. I declare a weak property:

@property (weak) NSString *weakString;

Then in viewDidLoad I assign a value to it:

self.weakString = [[NSString alloc] init];

Xcode marks that line with a warning that says:

Assigning retained object to weak property; object will be released after assignment

0
votes

If there is no object to strongly refer to "B", "B" will be deallocated. but, It is not sure if "B" will be deallocated immediately or not.

In your case with ARC, I assume that the "B" is an instance variable of "A", B would be deallocated immediately when "A" is deallocated. However, if "B" came to be registered in autorelease pool by ARC at any time, "B" will be deallocated at "next run loop cycle".