Collections of zeroing weak references under ARC

前端 未结 8 655
粉色の甜心
粉色の甜心 2020-12-23 14:05

How can I get an array of zeroing weak references under ARC? I don\'t want the array to retain the objects. And I\'d like the array elements either to remov

8条回答
  •  暖寄归人
    2020-12-23 14:37

    Just add a category for NSMutableSet with following code:

    @interface WeakReferenceObj : NSObject
    @property (nonatomic, weak) id weakRef;
    @end
    
    @implementation WeakReferenceObj
    + (id)weakReferenceWithObj:(id)obj{
        WeakReferenceObj *weakObj = [[WeakReferenceObj alloc] init];
        weakObj.weakRef = obj;
        return weakObj;
    }
    @end
    
    @implementation NSMutableSet(WeakReferenceObj)
    - (void)removeDeallocRef{
        NSMutableSet *deallocSet = nil;
        for (WeakReferenceObj *weakRefObj in self) {
            if (!weakRefObj.weakRef) {
                if (!deallocSet) {
                    deallocSet = [NSMutableSet set];
                }
                [deallocSet addObject:weakRefObj];
            }
        }
        if (deallocSet) {
            [self minusSet:deallocSet];
        }
    }
    
    - (void)addWeakReference:(id)obj{
        [self removeDeallocRef];
        [self addObject:[WeakReferenceObj weakReferenceWithObj:obj]];
    }
    @end
    

    Same way to create a category for NSMutableArray and NSMutableDictionary.

    Remove dealloc reference in didReceiveMemoryWarning will be better.

    - (void)didReceiveMemoryWarning{
        [yourWeakReferenceSet removeDeallocRef];
    }
    

    Then, what you should do is to invoke addWeakReference: for your container class.

提交回复
热议问题