添加新字符串后,对UITableVIew进行排序

时间:2013-11-08 21:57:01

标签: ios objective-c arrays uitableview sorting

我需要在添加新生成的随机字符串时对UITableView进行排序。

我有这段代码:

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd  target:self action:@selector(addRandomString)];

    self.navigationItem.rightBarButtonItem = addButton;

    UIBarButtonItem *sortButton = [[UIBarButtonItem alloc] initWithTitle:@"Sort" style:UIBarButtonItemStyleBordered target:self action:@selector(sortStrings)];

    self.navigationItem.leftBarButtonItem = sortButton;

    stringsArray = [[NSMutableArray alloc]init];
    int string_lenght = 10;
    NSString *symbols = @"ABCDEFGHIJKLMNOPQRSTUWXYZabcdefghijklmnopqrstuvwxyz";

    for (int y = 0; y<8; y++)
    {
        NSMutableString *randomString = [NSMutableString stringWithCapacity:string_lenght];

        for (int i = 0; i<string_lenght; i++)
        {
            [randomString appendFormat:@"%C", [symbols characterAtIndex:random()%[symbols length]]];
        }
        [stringsArray addObject:randomString];
    }
    stringsForTableView = [[NSMutableArray alloc]initWithArray:stringsArray];

}

- (void) addRandomString {

    int string_lenght = 10;

    NSString *symbols = @"ABCDEFGHIJKLMNOPQRSTUWXYZabcdefghijklmnopqrstuvwxyz";

    NSMutableString *randomString = [NSMutableString stringWithCapacity:string_lenght];

    for (int i = 0; i<string_lenght; i++)
    {
        [randomString appendFormat:@"%C", [symbols characterAtIndex:random()%[symbols length]]];
    }

    [stringsForTableView addObject:randomString];

    [self.tableView reloadData];
}

- (void) sortStrings{

    ??????????????????????

}

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

对可变数组使用标准排序函数:

[stringsForTableView sortUsingDescriptors:
         @[[NSSortDescriptor sortDescriptorWithKey:@"self" ascending:YES]]];
[self.tableView reloadData];