【问题标题】:Sort of an array from plist file对 plist 文件中的数组进行排序
【发布时间】:2012-05-12 16:59:34
【问题描述】:

我有一个包含字典的自定义 plist 文件。每个字典都包含关于一辆车的信息:

     <key>Ford</key>
<dict>
    <key>name</key>
    <string>Ford</string>
    <key>color</key>
    <string>green</string>
    <key>price</key>
    <integer>45000</integer>
</dict

    <key>Toyota</key>
<dict>
    <key>name</key>
    <string>Toyota</string>
    <key>color</key>
    <string>blue</string>
    <key>price</key>
    <integer>40000</integer>
</dict

    <key>BMW</key>
<dict>
    <key>name</key>
    <string>BMW</string>
    <key>color</key>
    <string>blue</string>
    <key>price</key>
    <integer>40000</integer>
</dict>

我还有一个 UITableView,我用这个 plist 中的一些汽车填充它。

 NSEnumerator *enumerator = [dictionary objectEnumerator];
    id returnValue;


    while ((returnValue = [enumerator nextObject])) 
    {

        if ([[returnValue valueForKey:@"color"]isEqualToString:@"blue")
        {  
            [array addObject:[returnValue valueForKey:@"name"]];
        }

问题:当我得到一个包含一些汽车的 UITableView 时,我现在如何按价格对它们进行排序?例如,宝马比福特便宜,所以它应该在第一个单元格中,而福特必须在第二个单元格中。我知道 Apple 已经创建了对数组进行排序的简单方法,但是我如何在这里使用它呢?谢谢 ! 最大

【问题讨论】:

    标签: iphone ios xcode ipad plist


    【解决方案1】:

    试试this:

    NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"price"  ascending:YES];
    [array sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
    

    【讨论】:

    • 谢谢!但是我的应用程序崩溃了:Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[&lt;__NSCFString 0x894c850&gt; valueForUndefinedKey:]: this class is not key value coding-compliant for the key price.'
    • 很好,很简单,而且很有帮助,兄弟。 + 1
    【解决方案2】:

    首先将 price 的值提取到列表中。然后使用 NSSorDescriptor。

    {
       NSArray *carArray=[[NSArray alloc] initwithContentsofFile:@"youFileName"    ofType:@"plist"];
       NSmutableArray *priceList=[[NSMutableArray alloc] init];
       for(int index=0;index<[carArray count];index++)
       {
          NSDictionary *valueList=[carArray objectAtIndex:index];
          [priceList addObject:[valueList objectForKey:@"Price"]];
    
       }
       NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"price"  ascending:YES];
       [priceList sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
    

    现在您将获得基于价格的排序数组。 }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-01
      • 2013-05-25
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 2018-05-08
      相关资源
      最近更新 更多