【问题标题】:Sorting an array of dictionaries in Plist在 Plist 中对字典数组进行排序
【发布时间】:2012-12-27 05:57:00
【问题描述】:

尝试对字典数组进行排序。 plist 文件中有两个数组,我正在尝试对其中一个进行排序,但遇到了很多麻烦。我可以将字典提取到 NSArray 中并对文件进行排序。

我只能通过提取字典来做到这一点,所以当我尝试将信息保存回 plist 时,我丢失了我的结构和其他字典数组。 如何正确排序数组。我知道我正在提取数组,然后将其保存为自己的文件。我知道我做错了什么,但无法弄清楚正确的方法。

NSArray *array =  [dict valueForKey:@"Lighting"];
NSSortDescriptor* nameSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Controller Zone" ascending:YES];
NSArray* sortedArray = [array sortedArrayUsingDescriptors:[NSArray arrayWithObject:nameSortDescriptor]];

NSString *pathToFileExportSorted = @"/Users/scott/Desktop/plistPreSEsorted.plist";
[sortedArray writeToFile:pathToFileExportSorted atomically: YES];

我尝试过类似的方法,但也无法正常工作

    [array sortUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"Lighting.Controller Zone" ascending:YES]]];

我只想按“控制器区域”对阵列照明进行排序,并保持 plist 不变。

感谢您的帮助。

原始数据:

我目前正在导出的内容没有照明和阴影阵列。数组现在是 plist 中唯一的东西。

【问题讨论】:

    标签: objective-c nsarray plist nsdictionary


    【解决方案1】:
    • 需要将排序后的数组分配给Lighting键
    • ...并使用更改的Lighting 键保存您的初始字典

      NSArray *array = [dict valueForKey:@"Lighting"];
      NSSortDescriptor *nameSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Controller Zone" ascending:YES];
      NSArray *sortedArray = [array sortedArrayUsingDescriptors:[NSArray arrayWithObject:nameSortDescriptor]];
      
      NSMutableDictionary *dictToSave = [[dict mutableCopy] autorelease];
      [dictToSave setObject:sortedArray forKey:@"Lighting"];
      
      NSString *pathToFileExportSorted = @"/Users/scott/Desktop/plistPreSEsorted.plist";
      [dictToSave writeToFile:pathToFileExportSorted atomically:YES];
      

    这应该像你描述的那样工作。

    【讨论】:

    • 我在寻找类似 set 对象的东西。谢谢你,我今晚会试试这个。
    猜你喜欢
    • 2018-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-30
    • 1970-01-01
    • 1970-01-01
    • 2016-07-14
    • 1970-01-01
    相关资源
    最近更新 更多