Weak object in an NSDictionary?

前端 未结 3 801
無奈伤痛
無奈伤痛 2020-12-28 16:23

I would like to store a zeroing weak reference to an object in a NSDictionary. This is for a reference to a parent NSDictionary, so I can crawl bac

3条回答
  •  轮回少年
    2020-12-28 16:53

    I've settled on defining a "container" class with a single member, like this:

    @interface Parent : NSObject
    @property (nonatomic, weak) id parent;
    @end
    
    @implementation Parent
    
    @synthesize parent = _parent;
    
    - (id)initWithParent: (id)parent;
    {
        if (( self = [super init] )) {
            _parent = parent;
        }
        return self;
    }
    @end
    

    And using it:

    id parentRef = [[Parent alloc] initWithParent: parent];
    [newElement setObject: parentRef forKey: ParentKey];
    

    I think this will work for me, but it seems crazy that there's no better way built in to Foundation.

提交回复
热议问题