首页 > 代码库 > __weak 和 __strong 还有Autorelease的用法
__weak 和 __strong 还有Autorelease的用法
使用容器的block版本的枚举器时,内部会自动添加一个AutoreleasePool:
Autorelease对象是在当前的runloop迭代结束时释放的,而它能够释放的原因是系统在每个runloop迭代中都加入了自动释放池Push和Pop
当然,在普通for循环和for in循环中没有,所以,还是新版的block版本枚举器更加方便。for循环中遍历产生大量autorelease变量时,就需要手加局部AutoreleasePool咯。
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { // 这里被一个局部@autoreleasepool包围着 }];
weak 和 strong 是iOS用于释放对象的一种机制,weak声明的对象,在原指针被释放之后,也会被会释放变成nil;
下面给出__weak和带__strong的代码和输出
@implementation AutoReleaseViewController__weak id reference;- (void)viewDidLoad{ [super viewDidLoad]; @autoreleasepool { NSString * str = [NSString stringWithFormat:@"xxxxx"]; reference = str; NSLog(@"str addr is %p",str); NSLog(@"reference addr is %p",reference); }}-(void)viewWillAppear:(BOOL)animated{ [super viewWillAppear:animated]; NSLog(@"reference addr is %p",reference); NSLog(@"view will appear reference :%@", reference);}-(void)viewDidAppear:(BOOL)animated{ [super viewDidAppear:animated]; NSLog(@"viewDidAppear reference: %@",reference);}@end//输出2014-11-01 19:40:34.480 AutoRelease[4506:60b] str addr is 0x8f328902014-11-01 19:40:34.480 AutoRelease[4506:60b] reference addr is 0x8f328902014-11-01 19:40:34.480 AutoRelease[4506:60b] reference addr is 0x02014-11-01 19:40:34.481 AutoRelease[4506:60b] view will appear reference :(null)2014-11-01 19:40:34.486 AutoRelease[4506:60b] viewDidAppear reference: (null)
@implementation AutoReleaseViewController__strong id reference;- (void)viewDidLoad{ [super viewDidLoad]; @autoreleasepool { NSString * str = [NSString stringWithFormat:@"xxxxx"]; reference = str; NSLog(@"str addr is %p",str); NSLog(@"reference addr is %p",reference); }}-(void)viewWillAppear:(BOOL)animated{ [super viewWillAppear:animated]; NSLog(@"reference addr is %p",reference); NSLog(@"view will appear reference :%@", reference);}-(void)viewDidAppear:(BOOL)animated{ [super viewDidAppear:animated]; NSLog(@"viewDidAppear reference: %@",reference);}@end//输出2014-11-01 19:41:20.872 AutoRelease[4669:60b] str addr is 0x8d42dd02014-11-01 19:41:20.872 AutoRelease[4669:60b] reference addr is 0x8d42dd02014-11-01 19:41:20.873 AutoRelease[4669:60b] reference addr is 0x8d42dd02014-11-01 19:41:20.873 AutoRelease[4669:60b] view will appear reference :xxxxx2014-11-01 19:41:20.877 AutoRelease[4669:60b] viewDidAppear reference: xxxxx
__weak 和 __strong 还有Autorelease的用法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。