Adding a category to NSArray

I added a category to NSArray with a helper method for sorting. My unit tests all pass, but when the application starts in the simulator, it explodes. Could this be due to the material of the NSMutableArray / NSCFArray class cluster ?

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

Anyway, what is the 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
+3
source share
5 answers

NSArray , , ( ).

" ", , , , . , .m , .

EDIT: , , NSArray .

EDIT # 2: Apple NSArray, , "" , . Citation ( NSArray)

+9

- , NSArray. NSArray , Apple ; , , .

, :

@interface MySortingArray : NSObject {
     NSArray *theArray
}

- (int)count;
- (NSArray *)sortBySequenceAsc;

@end

@implementation MySortingArray

- (int)count {
    return [theArray count];
}

- (NSArray *)sortBySequenceAsc {
   // your code
}

@end
+2

-, .

, , NSArray. NSMutableArray I, . , " ?". , .

, , . -, Apple NSMutableArray , NSArray. NSArray, ​​ NSMutableArray. NSMutableArray NSArray, NSArray NSMutableArray.

+2

NSArray... ... NSMutableArray, NSArray, .

+1

, - . NSArray, __NSCFArray, . : NSArray . ( isa) , .

, :

NSArray *array = [someObject someMethod];
// "array" may be a private class with the same methods as "NSArray", but not yours.

[array yourMethod];

:

NSArray *array = [NSArray arrayWithArray: [someObject someMethod]];
// "array" is now explicitly a "NSArray"

[array yourMethod];

It works, but I hope so. This is pretty unpredictable. This is why I created my own implementation of the array using open source here. I did not use methods that I do not need, and I added new ones that I may need (for example, shuffle). I am testing it now.

0
source

Source: https://habr.com/ru/post/1726715/


All Articles