码迷,mamicode.com
首页 > 其他好文 > 详细

ARC中strong、weak、unsafe_unretained的区别

时间:2014-10-14 19:57:39      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:arc

第一、strong关键字与retain关似,用了它,引用计数自动+1

如果person定义如下:

@interface Person : NSObject
@property(nonatomic,strong)Book *book1;
@end
(void)viewDidLoad {
    [super viewDidLoad];
    @autoreleasepool {
        p1=[[Person alloc] init];
        Book *book=[[Book alloc] init];
        p1.book1=book;
        NSLog(@"%@",p1.book1);
        book=nil;
    }
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    NSLog(@"%@",p1.book1);
}

输出结果:

2014-10-14 17:12:36.242 testDDD[9962:129809] <Book: 0x7f97b8e14210>
2014-10-14 17:12:36.243 testDDD[9962:129809] <Book: 0x7f97b8e14210>
即使在autorealease中执行了release,但因为retaincount加1,所以book所指的内存并没有被释放

第二、weak

声明为weak的指针,指针指向的地址一旦被释放,这些指针都将被赋值为nil。这样的好处能有效的防止野指针

如果person定义如下:

@interface Person : NSObject
@property(nonatomic,weak)Book *book1;
@end

(void)viewDidLoad {
    [super viewDidLoad];
    @autoreleasepool {
        p1=[[Person alloc] init];
        Book *book=[[Book alloc] init];
        p1.book1=book;
        NSLog(@"%@",p1.book1);
        book=nil;
    }
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    NSLog(@"%@",p1.book1);
}

输出结果:

2014-10-14 17:21:01.574 testDDD[10081:133743] <Book: 0x7fd0e8e5dc70>
2014-10-14 17:21:01.574 testDDD[10081:133743] (null)
第三、unretained且unsafe,由于是unretained所以与weak有点类似,但是它是unsafe的.
@interface Person : NSObject
@property(nonatomic,unsafe_unretained)Book *book1;
@end
(void)viewDidLoad {
    [super viewDidLoad];
    @autoreleasepool {
        p1=[[Person alloc] init];
        Book *book=[[Book alloc] init];
        p1.book1=book;
        NSLog(@"%@",p1.book1);
        book=nil;
    }
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    NSLog(@"%@",p1.book1);
}
结果为:

    crash
结果分析:p1执行内存被释放
unsafe_unretained声明的指针,由于book=nil已将内存释放掉了,但是string2并不知道已被释放了,所以是野指针。然后访问野指针的内存就造成crash.  所以尽量少用unsafe_unretained关键字


ARC中strong、weak、unsafe_unretained的区别

标签:arc

原文地址:http://blog.csdn.net/richard_rufeng/article/details/40080281

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!