You're misusing the the method indexOfObject:inSortedRange:
. That method should only be used on pre-sorted arrays, the array you're checking is not sorted. Your array is not sorted, since "Camper" would come before all of the other objects in that array. The indexOfObject:inSortedRange:
has undefined behavior when you give it an unsorted array.
Here's the correct way to do what you want. There are other NSArray
methods available for finding indexes, if you want to have different options or methods of determining equality.
NSMutableArray *original = [[NSMutableArray alloc] init];
NSMutableArray *new = [[NSMutableArray alloc] init];
[original addObject:@"Copy"];
[original addObject:@"Copy"];
[original addObject:@"Table"];
[original addObject:@"Table"];
[original addObject:@"Camper"];
[original addObject:@"Copy"];
for (NSString *string in original) {
NSUInteger i = [new indexOfObjectWithOptions:0 passingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
return [string compare:obj] == NSOrderedSame;
}];
if (i == NSNotFound) {
[new addObject:string];
}
NSLog(@"%lu", (unsigned long)i);
}
See NSArray documentation for more information.