質問

私のiphoneアプリは、キーと値のペアをplistファイル内の辞書に書き込みます。基本的に、ユーザーがゲームをプレイするときにユーザーのスコアを保存します。これはすべてうまくいきますが、アプリを実行して新しいスコアを取得するたびに、新しい値が古い値よりも保存されます。ユーザーがファイルを書き換える代わりにアプリにアクセスするたびに、plistに情報を追加するにはどうすればよいですか?最新のスコアだけでなく、すべてのスコアを保持したい。

コード:

-(void)recordValues:(id)sender {

    //read "propertyList.plist" from application bundle
    NSString *path = [[NSBundle mainBundle] bundlePath];
    NSString *finalPath = [path
                          stringByAppendingPathComponent:@"propertyList.plist"];
    dictionary = [NSMutableDictionary dictionaryWithContentsOfFile:finalPath];

    //create an NSNumber object containing the
    //float value userScore and add it as 'score' to the dictionary.
    NSNumber *number=[NSNumber numberWithFloat:userScore];
    [dictionary setObject:number forKey:@"score"];

    //dump the contents of the dictionary to the console 
    for (id key in dictionary) {
        NSLog(@"memory: key=%@, value=%@", key, [dictionary
                                                 objectForKey:key]);
    }

    //write xml representation of dictionary to a file
    [dictionary writeToFile:@"/Users/rthomas/Sites/propertyList.plist" atomically:NO];
}
役に立ちましたか?

解決

キースコアの数値にオブジェクトを設定しています

    NSNumber *number=[NSNumber numberWithFloat:userScore];   
 [dictionary setObject:number forKey:@"score"];

これの代わりに、あなたがしたいことは、配列またはソートのようなものを持っていることです

NSNumber *number=[NSNumber numberWithFloat:userScore];  
    NSMutableArray *array=[dictionary objectForKey:@"score"]
     [array addObject:number]
    [dictionary setObject:array forKey:@"score"]

これはあなたが尋ねていることをするはずです

他のヒント

ダニエルが言ったように、NSArrayまたはNSDictionaryに古い値を最初にロードしたい。

新しい値をコレクションに追加します。 (たぶんいくつかのソートまたは何かをする)

次に、新しいコレクションをディスクに書き戻します。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top