I have NSMutableArray* names, which contains NSStrings. I want to sort the array with the caseInsensitiveCompare method.
This is the code I’ve written:
names= [names sortedArrayUsingComparator: ^ NSComparisonResult (id obj1, id obj2)
{
return [obj1 caseInsensitiveCompare: obj2];
}];
The problem is that sortedArrayUsingComparator returns a NSArray instead of a NSMutableArray, and I get a warning and problems at runtime with this code.
Is there is a way to cast the NSArray to a NSMutableArray? Or do I have to copy all of the elements? This last solution is expensive: could someone suggest a nice, low overhead solution?
Note that the name of the function that you are using (
sortedArrayUsingComparator) tells you that it is going to return an array and not a mutable array. Use the mutableCopy method of NSArray to get a mutable copy.Or, easier to read / follow: