Collections of zeroing weak references under ARC

前端 未结 8 652
粉色の甜心
粉色の甜心 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:36

    Here's code for an a zeroing weak-referencing wrapper class. It works correctly with NSArray, NSSet, and NSDictionary.

    The advantage of this solution is that it's compatible with older OS's and that's it simple. The disadvantage is that when iterating, you likely need to verify that -nonretainedObjectValue is non-nil before using it.

    It's the same idea as the wrapper in the first part of Cocoanetics' answer, which uses blocks to accomplish the same thing.

    WeakReference.h

    @interface WeakReference : NSObject {
        __weak id nonretainedObjectValue;
        __unsafe_unretained id originalObjectValue;
    }
    
    + (WeakReference *) weakReferenceWithObject:(id) object;
    
    - (id) nonretainedObjectValue;
    - (void *) originalObjectValue;
    
    @end
    

    WeakReference.m

    @implementation WeakReference
    
    - (id) initWithObject:(id) object {
        if (self = [super init]) {
            nonretainedObjectValue = originalObjectValue = object;
        }
        return self;
    }
    
    + (WeakReference *) weakReferenceWithObject:(id) object {
        return [[self alloc] initWithObject:object];
    }
    
    - (id) nonretainedObjectValue { return nonretainedObjectValue; }
    - (void *) originalObjectValue { return (__bridge void *) originalObjectValue; }
    
    // To work appropriately with NSSet
    - (BOOL) isEqual:(WeakReference *) object {
        if (![object isKindOfClass:[WeakReference class]]) return NO;
        return object.originalObjectValue == self.originalObjectValue;
    }
    
    @end
    

提交回复
热议问题