2014-07-07 47 views
-1

我有NSarray包含動物列表。該數組包含具有重複元素的動物列表。我必須在數組中創建一個具有不同值的數組。 應使用NSPredicate刪除重複的值。如何使用NSPredicate對NSStrings的NSArray進行排序?

這裏是我的代碼: -

NSArray *arrAnimals = [[NSArray alloc] initWithObjects:@"Cat",@"Rat",@"Fish",@"Cat",@"Fish",@"Cat",@"Cat",@"Bird",@"Fish",@"Cat",@"Frog", nil]; 

NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"distinct"]]; 
arrAnimals = [arrAnimals filteredArrayUsingPredicate:predicate]; 

這裏我使用排序的數組「獨特」的關鍵字,但沒能找到任何解決方案。 我更喜歡很多鏈接。

http://www.infragistics.com/community/blogs/stevez/archive/2013/10/21/ios-objective-c-filtering-a-nsarray-using-nspredicate.aspx

請解決我的問題。

+0

是您的目標,以消除重複,還是按字母順序排序?或兩者? –

+0

http://stackoverflow.com/questions/1351182/how-to-sort-a-nsarray-alphabetically – Yogendra

+0

Yaah我的目標是刪除重複的條目和按字母順序排序。 – Apoorv

回答

1

您可以通過創建一個具有對象的集合並將其轉換回數組來移除數組中的重複項。

NSArray *arrAnimals = [[NSArray alloc] initWithObjects:@"Cat",@"Rat",@"Fish",@"Cat",@"Fish",@"Cat",@"Cat",@"Bird",@"Fish",@"Cat",@"Frog", nil]; 
NSArray *arrayWithoutDuplicates = [[NSSet setWithArray:arrAnimals] allObjects]; 
+0

此代碼適用於我。這將返回刪除重複值後的數組,而不使用NSPredicate。謝謝 – Apoorv

2

沒有斷言這一點,但您可以使用鍵值操作:

distinct = [array valueForKeyPath:@"@distinctUnionOfObjects.self"]; 
+0

感謝關鍵字「distinctUnionOfObjects.self」。這個方法也會返回排序後的數組。刪除重複值後。 – Apoorv

+0

它保留了順序,所以如果你的原始數組被排序,結果也會如此。 – Tricertops

0

試試這個由@iMartin回答

NSArray *arrAnimals = @[@"Cat",@"Rat",@"Fish",@"Cat",@"Fish",@"Cat",@"Cat",@"Bird",@"Fish",@"Cat",@"Frog"]; 

    arrAnimals= [arrAnimals valueForKeyPath:@"@distinctUnionOfObjects.self"]; 

    arrAnimals= [arrAnimals sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) { 
     unichar firstChar = [obj1 characterAtIndex:0]; 
     unichar secondChar = [obj2 characterAtIndex:0]; 

     if (firstChar == secondChar) { 
      return NSOrderedSame; 
     } else { 
      if (firstChar > secondChar) { 
       return NSOrderedDescending; 
      } else { 
       return NSOrderedAscending; 
      } 

     } 

    }]; 
相關問題