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
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)
The recommended way is to create a new object containing an NSArray
. Underneath NSArray
there's a lot of gunk that Apple doesn't tell us about; when you add new methods, you're unable to access that stuff, leading to errors.
Basically, do this:
@interface MySortingArray : NSObject {
NSArray *theArray
}
- (int)count;
- (NSArray *)sortBySequenceAsc;
@end
@implementation MySortingArray
- (int)count {
return [theArray count];
}
- (NSArray *)sortBySequenceAsc {
// your code
}
@end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With