iOS5中强弱存储的解释 [英] Explanation of strong and weak storage in iOS5

查看:13
本文介绍了iOS5中强弱存储的解释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 iOS5 开发和使用 Objective-c 的新手.我无法理解存储之间的区别.我已经阅读了文档和其他 SO 问题,但它们对我来说听起来都一样,没有进一步的洞察力.

I am new to iOS5 development and using objective-c. I have trouble understanding the difference between strong and weak storage. I have read the documentation and other SO questions, but they all sound identical to me with no further insight.

我阅读了文档:过渡到 ARC - 它引用了 iOS4 的保留、分配和释放条款;这让我很困惑.然后我研究了 Open U CS193p,它区分强弱:

I read the documentation: Transitioning To ARC - it references to iOS4 terms of retain, assign, and release; which confuses me. Then I look into Open U CS193p, where it differentiates strong and weak:

:将其保留在堆中,直到我不再指向它为止"
:只要有人强烈指出它就保持它"

Strong: "keep this in the heap until I don't point to it anymore"
Weak: "keep this as long as someone else points to it strongly"

这两个定义是不是相同的=如果指针不再指向一个对象,那么释放保存该对象的内存?我理解指针、堆、内存分配或释放的概念 - 但是强和弱之间有什么区别?

Aren't the two definition identical = if pointer no longer pointing to an object, then free the memory holding the object? I understand the concept of pointers, heap, allocation or deallocation of memory - but what's the difference between strong and weak?

推荐答案

不同之处在于,只要没有 strong 指针指向一个对象,它就会被释放.即使弱指针指向它,一旦最后一个强指针消失,对象将被释放,所有剩余的弱指针将被清零.

The difference is that an object will be deallocated as soon as there are no strong pointers to it. Even if weak pointers point to it, once the last strong pointer is gone, the object will be deallocated, and all remaining weak pointers will be zeroed out.

也许可以举个例子.

假设我们的对象是一只狗,而这只狗想要逃跑(被释放).

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.

一旦最后一个强指针(leash)不再指向一个对象,该对象将被释放,所有弱指针将被清零.

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.

这篇关于iOS5中强弱存储的解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆