2012-05-12 6 views
0

私は辞書を含むカスタムplistファイルを持っています。各辞書が一台の車に関する情報が含まれています: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を取得すると、どのように私は今の価格でそれらを並べ替えることができますか?たとえば、BMWはFordよりも安いので、最初のセルに入れる必要があり、Fordは2番目のセルに入れる必要があります。私はAppleが既に配列を並べ替える簡単な方法を作っていることを知っていますが、ここでどのように使うことができますか?ありがとう! マックス

答えて

3

thisで試してみてください。

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

ありがとうございます!しかし、私のアプリはクラッシュします: 'キャッチされていない例外 'NSUnknownKeyException'の理由でアプリを終了しています:理由: '[<__ NSCFString 0x894c850> valueForUndefinedKey:]:このクラスはキー価格に対応するキー値ではありません。' ' – SmartTree

+1

余分に役立つ仲間。 + 1 –

0

まずlist.Then使用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]]; 

今すぐ価格に基づいて並べ替えられた配列を取得します。 }