1

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{

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

}

谢谢你的帮助!

4

1 回答 1

2

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

[stringsForTableView sortUsingDescriptors:
         @[[NSSortDescriptor sortDescriptorWithKey:@"self" ascending:YES]]];
[self.tableView reloadData];
于 2013-11-08T22:08:15.720 回答