Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSArray of weak references (__unsafe_unretained) to objects under ARC

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

like image 226
Emile Cormier Avatar asked Feb 17 '12 22:02

Emile Cormier


People also ask

What is NSArray Objective C?

NSArray creates static arrays, and NSMutableArray creates dynamic arrays. You can use arrays when you need an ordered collection of objects. NSArray is “toll-free bridged” with its Core Foundation counterpart, CFArrayRef . See Toll-Free Bridging for more information on toll-free bridging.

Can NSArray contain nil?

arrays can't contain nil.


1 Answers

As Jason said, you can't make NSArray store weak references. The easiest way to implement Emile's suggestion of wrapping an object inside another object that stores a weak reference to it is the following:

NSValue *value = [NSValue valueWithNonretainedObject:myObj]; [array addObject:value]; 

Another option: a category that makes NSMutableArray optionally store weak references.

Note that these are "unsafe unretained" references, not self-zeroing weak references. If the array is still around after the objects are deallocated, you'll have a bunch of junk pointers.

like image 160
yuji Avatar answered Sep 24 '22 06:09

yuji