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
  • 51,574
  • 14
  • 135
  • 174
lakshmen
  • 27,102
  • 64
  • 169
  • 262

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
  • 307,833
  • 40
  • 508
  • 550
-1

try this,

NSArray *array=[[NSArray alloc]initWithObjects:@"Object1",@"object1", nil];      
array =[array sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
NSLog(@"%@",array);
Ravindhiran
  • 5,094
  • 9
  • 48
  • 80
  • 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