嘗試這樣的: -
NSDictionary *row1 = [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"rowId",nil];
NSDictionary *row2 = [NSDictionary dictionaryWithObjectsAndKeys:@"2",@"rowId",nil];
NSDictionary *row3 = [NSDictionary dictionaryWithObjectsAndKeys:@"3",@"rowId",nil];
NSMutableArray *arr = [[NSMutableArray alloc] initWithObjects:row1,row2,row3,nil];
NSSortDescriptor *desc = [[NSSortDescriptor alloc] initWithKey:@"rowId" ascending:YES];
[arr sortUsingDescriptors:[NSArray arrayWithObject:desc]];
// before sort
NSLog(@"Before %@",arr);
[arr sortedArrayUsingComparator:^(NSDictionary *item1, NSDictionary *item2) {
NSString *first = [item1 objectForKey:@"rowId"];
NSString *second = [item2 objectForKey:@"rowId"];
return [first compare:second options:NSNumericSearch];
}];
// After sort
NSLog(@"After %@",arr);
這是不正確。 OP聲明rowID是'NSString'對象,而不是'NSNumber'對象。這將最終做相同的不正確的字符串比較。 – rmaddy
它工作正常我的最後測試它,如果你發現不正確的結果,那麼我會刪除我的答案 – Leena
這是正確的,如果'rowID'值實際上是'NSNumber'對象,但OP有'NSString'對象。 – rmaddy