• 解决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;

  • 相关阅读:
    [ Openstack ] Openstack-Mitaka 高可用之 环境初始化
    [ Openstack ] OpenStack-Mitaka 高可用之 概述
    Swift
    Swift
    报错
    归并排序
    堆排序
    插入排序
    早睡早起身体好
    用于查询的日期类型转换帮助类
  • 原文地址:https://www.cnblogs.com/davidgu/p/4435352.html
Copyright © 2020-2023  润新知