ARC真的很简单!就像这幅图说的,让我们开发从最原始的状态,慢慢进化成了人,开发效率肯定是成倍的增长!这是令人激动的事情。。。但是ARC中还是有一些规则需要我们掌握,这样才能用好这个强大的工具。
1.多了一些关键字Lifetime Qualifiers
他们被苹果叫做生命限定符,那么就是说他们决定了对象的生死。那么接下来我们来看看他们是怎么样决定对象的生死的?
__strong__weak__unsafe_unretained__autoreleasing
__strong is the default. An object remains “alive” as long as there is a strong pointer to it.
strong是默认设置的。只要有一个指针指向它,那么这个对象就会保持“活跃”。
__weak specifies a reference that does not keep the referenced object alive. A weak reference is set to nil when there are no strong references to the object.
weak是指定一个没有保持引用对象活跃的引用。当没有一个strong对象引用的时候,一个weak引用将被设置为nil。(weak类型的指针也可以指向对象,但是并不会持有该对象。)
__unsafe_unretained specifies a reference that does not keep the referenced object alive and is not set to nil when there are no strong references to the object. If the object it references is deallocated, the pointer is left dangling.
__autoreleasing is used to denote arguments that are passed by reference (id *) and are autoreleased on return.
首先这些概念都是用来修饰指针的,而内存管理就是管理指针所指向的内存,只是用这些关键字,给指针添加了一些新的特性。
2.property和strong,weak
property也可以用strong或weak来标记,简单地把原来写retain和assign的地方替换成strong或者weak就可以了。
1
2
|
@property(nonatomic,strong)NSString*firstName;
@property (nonatomic,weak)id delegate;
|
3.那么到底哪些地方该使用strong,哪些地方该使用weak
strong很好理解,比如我有一个NSSting,如果我想长时间的拥有它,我就应该strong
那么weak呢?什么时候使用weak呢?
4.惯用法ldioms
1.以前手动管理的时候retain改成strong,assign的时候用weak
但是以前那些int,float型就不需要strong,weak了
2.在如果出现循环引用的时候使用weak,最典型的就是代理
5.参考文献
http://blog.youkuaiyun.com/favormm/article/details/7023322
http://blog.youkuaiyun.com/a2657222/article/details/7906995