R – Adding a category to NSArray

categoriesiphoneobjective c

I added a category to NSArray with a helper method for sorting. My unit tests all pass, but when running the app in the simulator it blows up. Could this be because of the NSMutableArray / NSCFArray class cluster stuff?

Here is the error:
'NSInvalidArgumentException', reason: '*** -[NSCFArray sortBySequenceAsc]: unrecognized selector sent to instance 0x489c1f0'

Anyway, what is the proper way to add a category to NSArray and NSMutableArray?

@interface NSArray (Util) 
- (NSArray *)sortBySequenceAsc;
@end 

@implementation NSArray (Util)
- (NSArray *)sortBySequenceAsc {
    //my custom sort code here
}
@end

Best Answer

I've used categories on NSArray many times with no problems, so I'm guessing your problem lies elsewhere (since your category looks correct).

Since you're getting an "unrecognized selector" error, that means the runtime doesn't know about your category, which means it wasn't linked into your binary. I would check and make sure your category's .m file is included in the appropriate target, clean, and build again.

EDIT: for example, this blog post shows how to create a category for NSArray for creating a shuffled copy of the original array.

EDIT #2: Apple's documentation on categories uses the specific example of extending the functionality of NSArray, so I find it difficult to believe that the "recommended" approach would be to wrap the array in a helper object. Citation (search the page for the five "NSArray" references)

Related Topic