0

I need to sort alphabetic data in a table view and ignore numbers, like :

- 123 test
- 939 urne
- 403 vase

Currently, data is loaded like this:

- 939 urne
- 123 test
- 403 vase

What's the best choice for ignoring numbers?

4

3 回答 3

1

您可以将数据单独存储在字典中,例如,

Array
(
   {  
      "number" = 403
      "text"   = "vase"
   },
   {  
      "number" = 403
      "text"   = "vase"
   }
)

然后你可以使用排序,

NSSortDescriptor * descriptor = [NSSortDescriptor sortDescriptorWithKey:@"text" ascending:YES];
[array sortUsingDescriptors:[NSArray arrayWithObject:descriptor]];
于 2013-08-26T04:31:53.607 回答
0

现在开始一个循环,其中包含您希望排序的数组中的所有对象。假设数组的名称是originalArray

NSMutableArray *newArray = [[NSMutableArray alloc] init];
NSMutableArray *finalArray = [[NSMutableArray alloc] init];

for(int i = 0; i < originalArray.count; i++)
{
    NSString *tempstr = [originalArray objectAtIndex:i]; // suppose it is 123 - abcd

    NSString *newString = [[tempstr componentsSeparatedByCharactersInSet: [[NSCharacterSet letterCharacterSet] invertedSet]] componentsJoinedByString:@""];

    NSDictionary *dict = [[NSDictionary alloc] init];  
    [dict setValue:@(i) forKey:@"num"];
    [dict setValue:newString forKey:@"char"];

    [newArray addObject:dict];

}

现在您可以排序newArray:-

NSSortDescriptor * descriptor = [NSSortDescriptor sortDescriptorWithKey:@"char" ascending:YES];
[newArray sortUsingDescriptors:[NSArray arrayWithObject:descriptor]];

现在您可以从该数组中存在的字典中获取索引(在键num下)

for(int j = 0; j<newArray.count ; j++)
{
    NSDictionary *dict1 = [[NSDictionary alloc] init];
    dict1 = [newArray objectAtIndex: j];
    int number = [[dict1 objectForKey:@"num"] intValue];
    NSString *str = [originalArray objectAtIndex:number];

//Now add this string in the finalArray. 

    [finalArray addObject:str];
}

我希望你能够理解这一点。:)

于 2013-08-26T06:57:28.460 回答
0

最好的方法

NSSortDescriptor *descriptor; = [NSSortDescriptor sortDescriptorWithKey:@"text" ascending:YES comparator:^(NSString *obj1, NSString *obj2) {

            return [obj1 compare:obj2 :NSCaseInsensitiveSearch];

        }];

    [arrDocuments sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
于 2013-08-26T05:02:23.590 回答