0

plistに格納されている辞書の配列があります。辞書キーは、globalKeyとmoneyKeyです。

次に、配列で特定のキー値を検索します。キー値が存在する場合は、他のキーの新しい値で辞書を更新する必要があります。

例:キー@ "globalKey"で値5を検索する必要があります。値5が存在する場合は、そのディクショナリをキー@ "moneyKey"の新しい値で更新し、plistに保存する必要があります。

これに対する最善のアプローチは何でしょうか?

これが私が新しい辞書を追加する方法です:

array = [NSMutableArray arrayWithContentsOfFile:filePath];
NSDictionary *newDict = [[NSDictionary alloc] init];
newDict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:month],@"globalKey", [NSNumber numberWithFloat:money], @"moneyKey", nil];
[array addObject:newDict];
[array writeToFile:filePath atomically:YES];
4

2 に答える 2

1

あなたが正しくやろうとしていることを理解していれば、次のようなことを試すことができると思います:

NSMutableArray *myArray = [[NSMutableArray alloc] init]; // YOUR STARTING ARRAY OF NSDICTIONARIES

NSMutableIndexSet *indexSet = [[NSMutableIndexSet alloc] init];
NSMutableArray *dictionariesToReplace = [[NSMutableArray alloc] init];

for (int i=0; i < [myArray count]; i++) 
{
    // Pull out the value to check
    int valToCheck = [[[myArray objectAtIndex:i] valueForKey:@"globalKey"] intValue];

    // Check if a match was made
    if (valToCheck == 5) 
    {
        // Make a copy of the existing NSDictionary
        NSMutableDictionary *newDictionary = [[myArray objectAtIndex:i] mutableCopy];
        [newDictionary setValue:@"NEW VALUE" forKey:@"moneyKey"];

        // Add the dictionary to the array and update the indexset
        [dictionariesToReplace addObject:newDictionary];
        [indexSet addIndex:i];
    }
}

// Update the array with the new dictionaries
[myArray replaceObjectsAtIndexes:indexSet withObjects:dictionariesToReplace];

これがお役に立てば幸いです。

于 2012-05-31T13:28:34.357 に答える
0

NSPredicate を使用して、次のように辞書の配列を検索できます。

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"globalKey == 5"]; NSArray *predicateArray = [arrayfilteredArrayUsingPredicate:predicate];

于 2012-05-31T13:26:04.867 に答える