Skip to content

Instantly share code, notes, and snippets.

@SheldonWangRJT
Last active August 5, 2018 02:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SheldonWangRJT/cb9561bea913824f8a73bf89b6ab1885 to your computer and use it in GitHub Desktop.
Save SheldonWangRJT/cb9561bea913824f8a73bf89b6ab1885 to your computer and use it in GitHub Desktop.
What Does "weak" Exactly Do in iOS?

What Does "weak" Exactly Do in iOS?

#iOSBySheldon

As we all know making an property weak is a good way to solve retain cycle or strong reference cycle. But do you know what does weak key-word exactly do behind the scene?

Two Quick Challenging Questions

  • Why weak property is nil after its owner object is released?
  • What exactly happened after weak property's owner object released?

Here is how Apple realize weak. Everything starts with iOS Runtime. Runtime maintenances a weak reference hash table, in which, it stores all the weak pointers and their corresponding owner objects. In this hash table, each key will be an object, each value will be an array of pointers.

class A {  
    weak var string = "some string"
}

When you initialize an weak property, Runtime will call objc_initWeak() to create a pointer.
When you instantiate an instance of your class, for example let a = A(), objc_initWeak() will call objc_storeWeak() to create the key-value pair into the weak reference hash table.
When you finish using your instance a, Runtime will call clearDeallocating(). It will use a as the key to find all the weak pointers that held by a and loop through all weak pointers to make them nil, and in the end, delete this key from the weak reference hash table.

Back To The Questions

Why weak property is nil after its owner object is released?
Runtime will create a hash table to store key-value pairs for owner object and its weak pointers. Once owner object is released, Runtime will loop through all the value pointers and make their values to be nil.

What exactly happened after weak property's owner object released?
Here are the steps:
1.object call objc_release()
2.because the reference counting is 0 for object, dealloc() will be executed
3.dealloc() will invoke objc_rootDealloc()
4.objc_rootDealloc() will invoke objc_dispose()
5.objc_destructInstance() will be called
6.objc_clear_deallocating() will be called in the end
7.objc_clear_deallocating() will clean the hash table, set all weak pointer's value as nil, and delete the key-value pair from the hash table.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment