1. 程式人生 > >ios中strong和weak的解釋理解

ios中strong和weak的解釋理解

來自stackoverflow解釋的挺有意思的

Imagine our object is a dog, and that the dog wants to run away (be deallocated). Strong pointers are like a leash on the dog. As long as you have the leash attached to the dog, the dog will not run away. If five people attach their leash to one dog, (five strong pointers to one object), then the dog will not run away until all five leashes are detached. Weak pointers, on the other hand, are like little kids pointing at the dog and saying "Look! A dog!" As long as the dog is still on the leash, the little kids can still see the dog, and they'll still point to it. As soon as all the leashes are detached, though, the dog runs away no matter how many little kids are pointing to it. As soon as the last strong pointer (leash) no longer points to an object, the object will be deallocated, and all weak pointers will be zeroed out. When we use weak? The only time you would want to use weak, is if you wanted to avoid retain cycles (e.g. the parent retains the child and the child retains the parent so neither is ever released).

weak/atrong主要是為了避免迴圈強引用   比如父類中含有子類{父類retain了子類},子類中又呼叫了父類{子類又retain了父類},這樣都無法release

這是裡面的關鍵。例子想想再寫,先發表吧。會宿舍碎覺~