1

I want to sort my array alphabetically in objective-c. I have implemented it this way.

//Sorting of the Array
NSArray *sortedArray = [arrName sortedArrayUsingComparator:^(Cars *firstObject, Cars *secondObject) {
    return [firstObject.str_name compare:secondObject.str_name];
}];
arrName =[NSMutableArray arrayWithArray:sortedArray];

The problem is all the numbers appear followed by captial letters words followed by lowercase letters items...

I want it to appear alphabetically-> meaning to say that the capital letters and lowercase letters maybe mixed.

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
lakshmen
  • 28,346
  • 66
  • 178
  • 276

2 Answers2

14

Replace compare: with caseInsensitiveCompare:.

Since arrName is mutable, use the 'sortUsingComparator' method instead. It will sort the mutable array in place without creating a new array.

[arrName sortUsingComparator:^(Cars *firstObject, Cars *secondObject) {
    return [firstObject.str_name caseInsensitiveCompare:secondObject.str_name];
}];
rmaddy
  • 314,917
  • 42
  • 532
  • 579
-1

try this,

NSArray *array=[[NSArray alloc]initWithObjects:@"Object1",@"object1", nil];      
array =[array sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
NSLog(@"%@",array);
Ravindhiran
  • 5,304
  • 9
  • 50
  • 82
  • This won't work. It's not an array of strings, it's an array of objects and the sort is on a property of the objects. – rmaddy Feb 19 '13 at 03:52