强引用与弱引用

转自:http://dcm19872007.blog.163.com/blog/static/8651937420131279318189/

若某个类完全拥有某个对象则使用强引用,否则使用弱引用。


觉得讲的很容易理解  

The difference is that an object will bedeallocated as soon as there are no strong pointersto 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 zeroedout.

Perhaps an example is in order.

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 havethe leash attached to the dog, the dog will not run away. If five people attachtheir leash to one dog, (five strong pointers to one object), then the dog willnot run away until all five leashes are detached.

Weak pointers, on the other hand, are like little kids pointingat the dog and saying "Look! A dog!" As long as the dog is still onthe leash, the little kids can still see the dog, and they'll still point toit. As soon as all the leashes are detached, though, the dog runs away nomatter how many little kids are pointing to it.

As soon as the last strong pointer (leash) no longer points toan object, the object will be deallocated, and all weak pointers will be zeroedout.

(weak和strong)不同的是 当一个对象不再有strong类型的指针指向它的时候它会被释放  ,即使还有weak型指针指向它。

一旦最后一个strong型指针离去 ,这个对象将被释放,所有剩余的weak型指针都将被清除。

可能有个例子形容是妥当的。

想象我们的对象是一条狗,狗想要跑掉(被释放)。

strong型指针就像是栓住的狗。只要你用牵绳挂住狗,狗就不会跑掉。如果有5个人牵着一条狗(5个strong型指针指向1个对象),除非5个牵绳都脱落,否着狗是不会跑掉的。

weak型指针就像是一个小孩指着狗喊到:“看!一只狗在那”只要狗一直被栓着,小孩就能看到狗,(weak指针)会一直指向它。只要狗的牵绳脱落,狗就会跑掉,不管有多少小孩在看着它。

只要最后一个strong型指针不再指向对象,那么对象就会被释放,同时所有的weak型指针都将会被清除。

 

 iOS 5中的strongweak关键字

iOS5 中对属性的设置新增了strong 和weak关键字来修饰属性(iOS 5 之前不支持ARC)

strong用来修饰强引用的属性;

@property (strong) SomeClass * aObject; 

对应原来的 

@property (retain) SomeClass * aObject; 和 @property (copy) SomeClass* aObject; 

 

weak用来修饰弱引用的属性;

@property (weak) SomeClass * aObject; 

对应原来的 

@property (assign) SomeClass * aObject; 

 

__weak,__strong 用来修饰变量,此外还有 __unsafe_unretained, __autoreleasing 都是用来修饰变量的。

__strong是缺省的关键词。

__weak声明了一个可以自动 nil 化的弱引用。

__unsafe_unretained声明一个弱应用,但是不会自动nil化,也就是说,如果所指向的内存区域被释放了,这个指针就是一个野指针了。

__autoreleasing用来修饰一个函数的参数,这个参数会在函数返回的时候被自动释放。

 

引申阅读:

Beginning ARC in iOS 5 Tutorial Part 1:http://www.raywenderlich.com/5677/beginning-arc-in-ios-5-part-1

ARC简介:http://blog.csdn.net/nicktang/article/details/6887569

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值