Search code examples
iosobjective-cnsarrayweak-references

How to store weak reference object in array, dictionary in objc?


As we know, when you add an object to an array (NSMutableArray) or dictionary (NSMutableDictionary), it create a strong reference to the object.

Is it possible to add an object to array with a weak reference to it?


Solution

  • 1.NSValue

    + (NSValue *)valueWithNonretainedObject:(id)anObject
    

    This method is useful if you want to add an object to a collection but don’t want the collection to create a strong reference to it.

    2.There is a tricky way use block to do so:

    typedef id (^WeakReference)(void);
    
    WeakReference MakeWeakReference (id object) {
        __weak id weakref = object;
        return ^{ return weakref; };
    }
    
    id WeakReferenceNonretainedObjectValue (WeakReference ref) {
        if (ref == nil)
            return nil;
        else
            return ref ();
    }
    
    [arr addObject:MakeWeakReference(obj)];
    id newobj = WeakReferenceNonretainedObjectValue([arr objectAtIndex:0]);
    

    3.Use a custom WeakReference class that hold on a weak pointer to the value.


    Actually, the design ideas of above methods are just the same.