سؤال

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?

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

You can use NSValue valueWithNonretainedObject: to strongly store a value that weakly references your target object.

NSMutableArray *arrayStrong = [NSMutableArray arrayWithObjects:
                                      [[yourClass alloc] init],
                                      [[yourClass alloc] init], nil];

NSPointerArray *arrayWeak = [NSPointerArray weakObjectsPointerArray];

for(yourClass *obj in arrayStrong){
    [arrayWeak addPointer:(__bridge void*)(obj)];
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top