strong or weak

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;

}


  • 还可以输入122
    |何时用 strong 或 weak 之二:


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部