NSPointerArray and collections of weak objects (Objective - C)

Darrell Kress / Thursday, April 10, 2014


There will be times when you want a collection of weak references.  Any one to many notification chain is just begging to introduce reference cycles more than willing to leak all over your application.  So when you have this situation in your application, you might want to consider the NSPointerArray.  Attached is an example of the NSPointerArray in action.

Code Sample

The NSPointerArray will allow you to either have a collection of strong or weak pointers and with nice little static call we can start using this collection.

NSPointerArray* myArray;
myArray = [NSPointerArray weakObjectsPointerArray];

Now rather than adding objects to the collection we explicitly add the pointers to the collection.

obj1 = [[UIView alloc]init];
obj1.tag = 100;
[myArray addPointer:(__bridge void *)obj1];

And if you want to get a value out of it, just use the pointerAtIndex: method to get the object out. The only caveat here is that since the collection is weak, than the pointer coming out may be a nil value.  

[myArray pointerAtIndex:someIndex];

As with many things related to APIs, seeing it in action is better than reading about it.  So I am attaching a sample showing how this works.

NSPointerArray Example Code

If you have a request for a feature in our frameworks, please let us know and we will see what can be done. 

Questions about a feature?  Hit us on the NucliOS Forums.

And if you have a request for a how to article for the NucliOS product you can tweet it to the @Infragistics feed or myself @DarrellKress17 and we will see if we can write that up for you.

By Darrell Kress