2011-04-28 108 views
17

我必須通過作爲字符串的對象的屬性對對象數組進行排序。 我該怎麼做?Objective C - 排序字符串數組

+0

的可能重複的[在assending順序排序陣列..?](http://stackoverflow.com/questions/5816017/sort-array-in-assending-order) – Vladimir 2011-04-28 15:23:34

回答

35

你需要使用

-[NSArray sortedArrayUsingSelector:] 

-[NSMutableArray sortUsingSelector:],並通過@selector(compare:)作爲參數。

這裏的答案 Sort NSArray of date strings or objects

3

鏈接這裏是我最終使用;就像一個魅力:

[categoryArray sortedArrayWithOptions:0 
       usingComparator:^NSComparisonResult(id obj1, id obj2) 
{ 
    id<SelectableCategory> cat1 = obj1; 
    id<SelectableCategory> cat2 = obj2; 
    return [cat1.name compare:cat2.name options:NSCaseInsensitiveSearch]; 
}]; 

SelectableCategory只是一個@protocol SelectableCategory <NSObject>定義與它的所有屬性和元素的類別。

5

對於剛剛排序字符串數組:

sorted = [array sortedArrayUsingSelector:@selector(compare:)]; 

對於排序與鍵 「name」 對象:

NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(compare:)]; 
sorted = [array sortedArrayUsingDescriptors:@[sort]]; 

另外,代替compare:你可以使用:

  • caseInsensitiveCompare:

  • localizedCaseInsensitiveCompare: