I am receiving a weird sort error. I have a list of ranges in an array called wordArrayDuplicates. I need to sort this array based on range location so i convert the string to an NSNumber but it wont compare.
* Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘-[__NSCFString
sortedArrayUsingComparator:]:
- (NSArray *)sortedArray {
if (!sortedArray) {
sortedArray = [[NSArray alloc]init];
}
return [wordArrayDuplicates sortedArrayUsingComparator:(NSComparator)^(id obj1, id obj2){
NSNumber * lastName1 = [NSNumber numberWithInt:NSRangeFromString(obj1).location];
NSNumber * lastName2 = [NSNumber numberWithInt:NSRangeFromString(obj2).location];
return [lastName1 compare:lastName2]; }];
}
-(void)beginGoingThroughDuplicatesAtWordIndex:{
if (index == 1) {[self loadDuplicates];}
[string addAttribute:(id)kCTForegroundColorAttributeName
value:(id)[UIColor blackColor].CGColor
range:NSMakeRange(0, string.length)];
BOOL shouldContinue = YES;
while (shouldContinue == YES && index<[[self sortedArray] count]) {
if (![[tv.text substringWithRange:NSRangeFromString([[self sortedArray] objectAtIndex:index-1])] isEqualToString:[tv.text substringWithRange:NSRangeFromString([[self sortedArray] objectAtIndex:index])]]) {
shouldContinue = NO;
}
[string addAttribute:(id)kCTForegroundColorAttributeName
value:(id)[UIColor redColor].CGColor
range:NSRangeFromString([sortedArray objectAtIndex:index-1])];
index++;
}
textlayer.string = string;
}
When you sort the array using
sortedArrayUsingSelector:, as inyou are passing the selector which is going to be called on each of the objects in the array. So you must be providing some method that is implemented in the objects that’s in the array. For example,
compare:, a standard method forNSString:You are passing another
NSArraymethod. You must choose, either you want to sort using selector or using comparator, but you cannot call one inside of the other.In your example in
- (NSArray *)sortedArrayyou are usingsortedArrayUsingComparator:correctly, stick to that way.Usage recommendation
In general, one should use
sortedArrayUsingComparator:when sorting array from one place of the code, to avoid creating selectors in the object classes.When sorting is being called from many places in the code, then creating a selector may be more useful. Even if it isn’t your own object and you’re just sorting
NSStringin some special way, you can create a category onNSStringwith somecustomCompare:method and use it.