What's going on with __weak qualified variables under the hood?

automatic-ref-counting, memory-management, objective-c, weak-references

Solution

The following is your friend:

- http://clang.llvm.org/docs/AutomaticReferenceCounting.html

And also the source for the Objective-C runtime:

- http://www.opensource.apple.com/source/objc4/objc4-493.9/runtime/

In particular, take a look at:

- http://www.opensource.apple.com/source/objc4/objc4-493.9/runtime/objc-arr.mm

- http://www.opensource.apple.com/source/objc4/objc4-493.9/runtime/objc-weak.mm

If you look at `objc_initWeak` and `objc_destroyWeak` as per the 1st link talks about then you'll see how it works "under the hood". The guts is in `weak_register_no_lock` for registering a weak reference and in `weak_unregister_no_lock` for unregistering a weak reference.

I'll leave it up to you to go through and see all the intricacies around how it actually works :-).

Problem

Usually `weak` references are used to avoid retain cycles in the application object graph. I understand that part. Now I would like to go a step further and understand how they work under the hood. Searching a bit, I've read that when I'm using the `__weak` qualifier, the variable associated with that qualifier is registered in an autorelease pool, but what does this mean? Why is the object registered in the pool? What type of pool is used? Is it the main pool or some other specially created one? When I use this code: ``` id _weak myWeakObj = [[NSObject alloc] init]; ``` the compiler gives me a warning that I can fix with: ``` id _strong myStrongObj = [[NSObject alloc] init]; id _weak myWeakObj = myStrongObj; ``` So, based on the previous question, what happens to the object referenced by `myStrongObj`? If possible, I'd like to know what the compiler's code looks like?

Original source

Related problems