Objective-c字符串和布尔的最佳数据结构排序

Objective-c字符串和布尔的最佳数据结构排序,objective-c,string,sorting,boolean,nsdictionary,Objective C,String,Sorting,Boolean,Nsdictionary,我需要在TableView中为我的项目存储一个字符串列表,并为每个字符串存储一个布尔值。。我会使用NSDictionary,但如何按字母顺序对字符串列表进行排序(使用选择器)并同时对布尔值进行排序 我知道存在sortUsingSelector或UsingComparator等方法,但在NSDictionary中,我只能按值对键进行排序,所以我需要相反的方法 有人能帮我吗,也许可以使用另一种数据结构?我建议使用以下数据结构: 使用NSArray NSDictionary,如下所示(使其成为属性):

我需要在TableView中为我的项目存储一个字符串列表,并为每个字符串存储一个布尔值。。我会使用NSDictionary,但如何按字母顺序对字符串列表进行排序(使用选择器)并同时对布尔值进行排序

我知道存在sortUsingSelector或UsingComparator等方法,但在NSDictionary中,我只能按值对键进行排序,所以我需要相反的方法


有人能帮我吗,也许可以使用另一种数据结构

我建议使用以下数据结构:

使用NSArray NSDictionary,如下所示(使其成为属性):

然后可以按如下方式对其进行排序:

self.array = [self.array sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *aDictionary, NSDictionary *anotherDictionary) {
    return [aDictionary[@"String"] compare:anotherDictionary[@"String"]];
}];
如果要填充UITableView,只需执行以下操作:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.array.count; //If you want them all in one section, easiest case
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // ...
    // Do all the initialization of your cell
    // ...

    cell.yourLabel.text = self.array[indexPath.row][@"String"];
    cell.yourSwitch.on = ((NSNumber *)self.array[indexPath.row][@"bool"]).boolValue;
    return cell;
}

如果您对键进行排序,那么值本身就是被排序的,因为您使用键来访问值。为什么不创建一个字典数组呢?每本字典都包含一个字符串和一个布尔。然后可以使用字符串对数组进行排序;)我用一些技巧找到了解决办法,然后四处走走。。非常感谢您的回答,您已经帮助我这么做了。如何像您那样在NSMutableArray中插入新的dictionary对象?我指的是addObject的等价物:对于普通数组,你不能。“普通”数组是不可变的(一旦初始化就不能更改它)。这就是你的
alloc init
@[]
的时候,你不能再更改它的内容了,但是由于我们使用指针,我们可以轻松地创建一个新数组,并让指针指向新创建的数组。我不能一次全部填充。。我需要在迭代中逐个填充。所以,如果我使用NSMutableArray,我就无法遵循您的方法?@Shafa95您的问题毫无意义。您声明已经使用了
NSMutableArray
。您声称您知道
addObject:
如何处理它。问题是什么?我会这样做:
//PROVA数组NSMutableDictionary*dizionario=[[NSMutableDictionary alloc]init];[dizionario setObject:@“记录[i][tipologia]”forKey:@“项目”];[dizionario setObject:0 forKey:@“Bool”];[Listanonnordinata addObject:dizionario]对吗?
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.array.count; //If you want them all in one section, easiest case
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // ...
    // Do all the initialization of your cell
    // ...

    cell.yourLabel.text = self.array[indexPath.row][@"String"];
    cell.yourSwitch.on = ((NSNumber *)self.array[indexPath.row][@"bool"]).boolValue;
    return cell;
}