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

解决ARC的循环引用问题

时间:2015-04-17 17:35:13      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:

看看下面的程序有什么问题:

BNRItem.h

@interface BNRItem : NSObject

@property (nonatomic, strong) BNRItem *containedItem;
@property (nonatomic, strong) BNRItem *container;

...

@end

 

BNRItem.m

#import "BNRItem.h"

@implementation BNRItem

...

- (void)setContainedItem:(BNRItem *)containedItem
{
    _containedItem = containedItem;
    self.containedItem.container = self;
}

@end


main.m

int main(int argc, const char * argv[])
{

    @autoreleasepool {

        // Create a mutable array object, store its address in items variable
        NSMutableArray *items = [[NSMutableArray alloc] init];

        BNRItem *backpack = [[BNRItem alloc] initWithItemName:@"Backpack"];
        [items addObject:backpack];

        BNRItem *calculator = [[BNRItem alloc] initWithItemName:@"Calculator"];
        [items addObject:calculator];

        backpack.containedItem = calculator;

        backpack = nil;
        calculator = nil;

        for (BNRItem *item in items) {
            NSLog(@"%@", item);
        }

        // Destroy the mutable array object
        NSLog(@"Setting items to nil...");
        items = nil;

    }
    return 0;
}

 

上面的程序是有问题的,会导致循环引用(strong reference cycle)。

导致内存泄露。

 

解决方案:

将某个指针的特性设置为弱引用

@property (nonatomic, weak) BNRItem *container;

 

解决ARC的循环引用问题

标签:

原文地址:http://www.cnblogs.com/davidgu/p/4435352.html

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