I need to store weak references to objects in an NSArray, in order to prevent retain cycles. I'm not sure of the proper syntax to use. Is this the correct way?
Foo* foo1 = [[Foo alloc] init];
Foo* foo2 = [[Foo alloc] init];
__unsafe_unretained Foo* weakFoo1 = foo1;
__unsafe_unretained Foo* weakFoo2 = foo2;
NSArray* someArray = [NSArray arrayWithObjects:weakFoo1, weakFoo2, nil];
Note that I need to support iOS 4.x, thus the __unsafe_unretained
instead of __weak
.
EDIT (2015-02-18):
For those wanting to use true __weak
pointers (not __unsafe_unretained
), please check out this question instead: Collections of zeroing weak references under ARC
If you need zeroing weak references, see this answer for code you can use for a wrapper class.
Other answers to that question suggest a block-based wrapper, and ways to automatically remove zeroed elements from the collection.
No, that's not correct. Those aren't actually weak references. You can't really store weak references in an array right now. You need to have a mutable array and remove the references when you're done with them or remove the whole array when you're done with it, or roll your own data structure that supports it.
Hopefully this is something that they'll address in the near future (a weak version of
NSArray
).If you do not require a specific order you could use
NSMapTable
with special key/value optionsIf you use a lot this comportment it's indicated to your own NSMutableArray class (subclass of NSMutableArray) which doesn't increase the retain count.
You should have something like this:
To add weak self reference to NSMutableArray, create a custom class with a weak property as given below.
Step 3: later on, if the property
delegateWeakReference == nil
, the object can be removed from the arrayThe property will be nil, and the references will be deallocated at proper time independent of this array references
I've just faced with same problem and found that my before-ARC solution works after converting with ARC as designed.
Output:
Checked with iOS versions 4.3, 5.1, 6.2. Hope it will be useful to somebody.