__unsafe_unretained ownership qualifier

__unsafe_unretained ownership qualifier
1.介绍
_unsafe_unretained修饰的变量不是线程安全的,使用它修饰的任何变量排除在ARC(由编译器执行内存管理),程序员需手动管理。
2.造成悬挂指针
Listing 2–9. _unsafe_unretained qualifier
id __unsafe_unretained obj1 = nil;
{
id __strong obj0 = [[NSObject alloc] init];
obj1 = obj0;
NSLog(@”A: %@”, obj1); }
NSLog(@”B: %@”, obj1);
The result is:
A:
B:
Let’s see the source code again with comments as usual (Listing 2–10).
Listing 2–10. _unsafe_unretained qualifier with comments id __unsafe_unretained obj1 = nil;
{
/*
* You create an object and have ownership. */
id __strong obj0 = [[NSObject alloc] init];
/*
* The variable obj0 is qualified with __strong. * Which means, it has ownership of the object. */
obj1 = obj0;
/*
* variable obj1 is assigned from variable obj0,
* obj1 does not have either strong or weak reference */
NSLog(@”A: %@”, obj1);
/*
* Display the value of obj1 */

} /*
* Leaving the scope of variable obj0, its strong reference disappears. 

* The object is released automatically.
* Because no one has ownership, the object is discarded. */
NSLog(@“B: %@”, obj1); 
/* 

* Display the value of obj1 * 

* The object referenced from obj1 is already discarded. 

* It is called dangling pointer.
* Invalid access!!
*/ 

__unsafe_unretain在对象离开作用域的时候就会释放,obj1声名的时候是强引 用,引用计数为1,obj0赋值不会增加引用计数,作用域结束,obj1就会release引用计数为0,对象释放,但是obj0中仍然存放着之前的地址,没有清空,所以继续使用就会不安全unsafe

__weak弱引用,主要是为了解决循环引用造成的内存泄漏问题,在离开作用域的时候会将指针赋值null,从而在之后不可以继续使用

(3) __autoreleasing ownership qualifier

在non-ARC与ARC下使用

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
id obj = [[NSObject alloc] init]; 
[obj autorelease]; 
[pool drain];
等价与下面代码
@autoreleasepool {
id __autoreleasing obj = [[NSObject alloc] init]; 
} 


这里写图片描述

使用@autoreleasing块取代NSAutoreleasePool对象的创建、保持以及销毁。
通过分配给用_autoreleasing修饰的变量一个对象,来代替调用autoreleasing方法

为什么不经常使用_autoreleasing
因为编译器会帮我们处理。当一个方法返回一个对象时,编译器会核对是否在方法开始使用alloc、new、copy、mutableCopy等方法,如果不是,那么这个对象会自动在释放池中进行注册。如果没有使用alloc、new、copy、mutableCopy它们创建对象来持有一个对象,那么这个对象将自动在释放池中注册。
_weak与释放池
1)被_weak修饰的对象,总是注册在释放池中。
id __weak obj1 = obj0;
NSLog(@”class=%@”, [obj1 class]);
等价与
id __weak obj1 = obj0;
id __autoreleasing tmp = obj1;
NSLog(@”class=%@”, [tmp class]);
2)为什么经常使用_weak?使用_weak修饰的变量,可能在任何时候被销毁,如果对象被注册在释放池时,直到@autoreleasepool块消失对象才被释放,所以使用_weak变量修饰的变量安全,对象被自动添加到释放池中
任何指向id或对象类型的指针默认被_autoreleading修饰。
例如:id *obj不等于id _strong *obj.而等价于id _autoreleaseing *obj
NSObject **obj 等价与NSObject *_autoreleasing *obj.
有时一个方法通过一个指针类型的NSError对象作为参数来传递错误信息。例如NSString类中的stringWithContentsOfFile:encoding:error方法。

————-第50页

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员的修养

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值