2011-06-18 8 views
0

私がしたいのは、スコアリストに名前を追加することです。現在、NSStringとして保存されている名前を持っていて、得点が整数として保存され、後でこれらを高い値から低い値(スコア)に並べ替える必要があります。以下はplistに整数としてスコアを保存している私のコードですが、私のハイスコアビューではplistからそのスコアを呼び出して表示しています。名前の文字列とスコアの整数を保存するにはNSDictionaryを使う必要があると思います。これは私が立ち往生して誰かがそれを助けることができれば大いに感謝されるでしょう。ハイスコア(iPhoneアプリ)で名前を表示

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 

NSString *scoresListPath = [documentsDirectory stringByAppendingPathComponent:@"scores.plist"]; 

scoresList = [[NSMutableArray arrayWithContentsOfFile:scoresListPath] retain]; 

if (scoresList == nil) { 
    scoresList = [[NSMutableArray array] retain]; 




- (void)addHighScore:(float)finalScore { 
    [scoresList addObject:[NSNumber numberWithFloat:finalScore]]; 

    [scoresList sortUsingSelector:@selector(compare:)]; 

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 

    NSString *scoresListPath = [documentsDirectory stringByAppendingPathComponent:@"scores.plist"]; 
    [scoresList writeToFile:scoresListPath atomically:YES]; 
} 

答えて

0

あなたは正しい基本的な考え方を持っていますが、代わりにNSNumbersの配列だけを保存するので、あなたがしなければならないすべてはNSDictionariesの配列を保存しています。

だからあなたのNSMutableArrayのそれは方法を維持し、単にそれにスコアを追加します。

NSDictionary *score = [NSDictionary dictionaryWithObjectAndKeys: theName, @"name", [NSNumber numberWithFloat:finalScore], @"finalScore", nil]; 
[scoresList addObject: score]; 

NS [変更可能な]配列は、数値のみが含まれている辞書が含まれているためscoreListはまだ、適切にそのplistのを書き出しますこれらは、自分自身をplistに書く方法を知っています(NSCoderを参照)。

アレイを読み返すと、-objectAtIndex:iはNSDictionaryになり、-objectForKey:@ "name"でスコアを取得し、-objectForKey:@ "finalScore"でスコアを取得できます。

関連する問題