Guest User

Untitled

a guest
Mar 24th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. #iOSBySheldon
  2.  
  3.  
  4. 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?
  5.  
  6.  
  7. Two quick challenging questions for you guys.
  8.  
  9. Why weak property is nil after its owner object is released?
  10. What exactly happened after weak property's owner object released?
  11.  
  12.  
  13. 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.
  14.  
  15.  
  16. class A {
  17.  
  18. weak var string = "some string"
  19.  
  20. }
  21.  
  22.  
  23. When you initialize an weak property, Runtime will call objc_initWeak() to create a pointer.
  24. 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.
  25. 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.
  26.  
  27.  
  28. Now we can answer the two questions I asked you guys.
  29.  
  30. Why weak property is nil after its owner object is released?
  31.  
  32. 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.
  33.  
  34. What exactly happened after weak property's owner object released?
  35.  
  36. Here are the steps:
  37.  
  38. object call objc_release()
  39. because the reference counting is 0 for object, dealloc() will be executed
  40. dealloc() will invoke objc_rootDealloc()
  41. objc_rootDealloc() will invoke objc_dispose()
  42. objc_destructInstance() will be called
  43. objc_clear_deallocating() will be called in the end
  44. 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.
Add Comment
Please, Sign In to add comment