何时用 strong 或 weak

转:点击打开链接 点击打开链接

1、weak 没有自主占有权,strong 侧有。

@interface WBViewController : UIViewController
   @property(nonatomic, strong) NSArray *arrayStrong;
    @property(nonatomic, weak) NSArray *arrayWeak;
@end

#import "WBViewController.h"

@implementation WBViewController
- (void)viewDidLoad{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self aFunction];
}

-(void)aFunction{
NSArray *array = [[NSArray alloc] initWithObjects:@"1",@"2", nil];
NSArray *array2= [[NSArray alloc] initWithObjects:@"3",@"4", nil];
self.arrayStrong = array;
self.arrayWeak = array2;

//arrayStrong 独立占有内存,当array释放后依然保留
array = nil;

//arrayWeak 不占有内存,它的死活由外部(array2)决定, 当array2 释放后它也被释放。
array2= nil;

NSLog( @"Strong: %@, weak: %@", self.arrayStrong, self.arrayWeak);
}
@end

输出:2014-04-01 11:07:14.126 Weibo[3793:a0b] Strong: (1,2), weak: (null)

2、weak 可避免死循环。

@class ClassA;
@interface WBViewController : UIViewController
@property(nonatomic, strong) ClassA *classA;
@end

@interface ClassA : NSObject
//为避免死循环,这里应该改为 weak
@property(nonatomic, strong) WBViewController *controller;
@end

@implementation WBViewController
- (void)viewDidLoad{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
ClassA *aClass = [[ClassA alloc] init];
aClass.controller = self;
// 出错!self.classA 为strong, aClass.controller 也是strong,
// 以下赋值会引起引用传说中的死循环(retain cycle)
//
// 当系统要释放 aClass 时,发现 aClass 有strong reference (controller), 得先释放 controller,
// 轮到释放 controller 时,又发现 controller 他妈的也有 strong reference (classA), 于是又去释放他妈的 classA...
// 泥马就他妈的这样不断的循环下去,系统很繁忙,很快就阳痿了。。。
self.classA = aClass;
}



 

posted @ 2014-05-04 22:34  Forrest.Wang  阅读(155)  评论(0编辑  收藏  举报