__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 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

 

你可能感兴趣的:(auto)