标签:
@interface CustomedObj:NSObject + (instancetype) methodInit; @end @implementation CustomedObj + (instancetype)methodInit { CustomedObj *temp = [[CustomedObj alloc] init]; return temp; } - (void) print { NSLog(@"==== Customed Object print"); } - (void)dealloc { NSLog(@"对象即将被析构"); } @end
@autoreleasepool {
__weak CustomedObj *weakRef = [CustomedObj methodInit];// 对象自动注册至autoreleasepool,执行完retainCount=1
[weakRef print];//执行完retainCount=1
}
NSLog(@"退出 autoreleasepool”);
Log:
==== Customed Object print
对象即将被析构
退出 autoreleasepool
3.2 alloc/new/copy/mutableCopy获取对象,不会自动注册至autoreleasepool,必须主动强持有以保证不被析构
@autoreleasepool {
__weak CustomedObj *weakRef = [[CustomedObj alloc] init];//编译警告,对象析构
[weakRef print]; // print消息将被发至nil
}
NSLog(@"退出 autoreleasepool”);
LOG:
对象即将被析构
退出 autoreleasepool
3.3 weak指针被访问时,如未注册,系统自动将对象注册至autoreleasepool,引用计数增加
@autoreleasepool {
CustomedObj *strongRef = [CustomedObj methodInit];//变量默认为__strong,因为编译器优化,将不会注册至autoreleasepool, retainCount=1
__weak CustomedObj *weakRef = strongRef;
[weakRef print];//调用weak指针会将对象注册到autoreleasepool,执行完retainCount=2
}
NSLog(@"退出 autoreleasepool");
LOG:
==== Customed Object print
对象即将被析构
退出 autoreleasepool
标签:
原文地址:http://www.cnblogs.com/hushuai-ios/p/5165049.html