标签: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); }结果为:
ARC中strong、weak、unsafe_unretained的区别
标签:arc
原文地址:http://blog.csdn.net/richard_rufeng/article/details/40080281