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

__weak 和 __strong 还有Autorelease的用法

时间:2014-11-01 20:22:42      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   os   ar   使用   for   sp   

使用容器的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 0x8f32890
2014-11-01 19:40:34.480 AutoRelease[4506:60b] reference addr is 0x8f32890
2014-11-01 19:40:34.480 AutoRelease[4506:60b] reference addr is 0x0
2014-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 0x8d42dd0
2014-11-01 19:41:20.872 AutoRelease[4669:60b] reference addr is 0x8d42dd0
2014-11-01 19:41:20.873 AutoRelease[4669:60b] reference addr is 0x8d42dd0
2014-11-01 19:41:20.873 AutoRelease[4669:60b] view will appear reference :xxxxx
2014-11-01 19:41:20.877 AutoRelease[4669:60b] viewDidAppear reference: xxxxx

 

__weak 和 __strong 还有Autorelease的用法

标签:style   blog   io   color   os   ar   使用   for   sp   

原文地址:http://www.cnblogs.com/zuopeng/p/4067642.html

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