解决ARC的循环引用问题

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

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;

 

posted @ 2015-04-17 16:39  Master HaKu  阅读(326)  评论(0编辑  收藏  举报