1

plist ファイルから整数を取得し、それをインクリメントして、plist ファイルに書き戻したいと考えています。「Levels.plist」ファイル内には、キーLevelNumberが で値がの行があります1。このコードを使用して値を取得します。

NSString *filePath = [[NSBundle mainBundle]pathForResource:@"Levels.plist" ofType:@"plist"];;
    NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
    lvl = [[plistDict objectForKey:@"LevelNumber"]intValue];
    NSLog(@"%i", [[plistDict objectForKey:@"LevelNumber"]intValue]);

これを実行すると、コンソール出力が 0 になります。何が間違っているのか教えてもらえますか?

4

3 に答える 3

2

途中で多くのエラーチェックを行う必要があるようです。

おそらく次のようなものです:

NSString *filePath = [[NSBundle mainBundle]pathForResource:@"Levels" ofType:@"plist"];
if(filePath)
{
    NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
    if(plistDict)
    {
        NSNumber * lvlNumber = [plistDict objectForKey:@"LevelNumber"];
        if(lvlNumber)
        {
            NSInteger lvl = [lvlNumber integerValue];

            NSLog( @"current lvl is %d", lvl );

            // increment the found lvl by one
            lvl++;

            // and update the mutable dictionary
            [plistDict setObject: [NSNumber numberWithInteger: lvl] forKey: @"LevelNumber"];

            // then attempt to write out the updated dictionary
            BOOL success = [plistDict writeToFile: filePath atomically: YES];
            if( success == NO)
            {
                NSLog( @"did not write out updated plistDict" );
            }
        } else {
            NSLog( @"no LevelNumber object in the dictionary" );
        }
    } else {
        NSLog( @"plistDict is NULL");
    }
} 
于 2012-07-19T02:59:23.507 に答える
1
NSString *filePath = [[NSBundle mainBundle] 
          pathForResource:@"Levels.plist" ofType:@"plist"];

NSMutableDictionary* plistDict = [[NSMutableDictionary alloc]
                          initWithContentsOfFile:filePath];
lvl = [[plistDict objectForKey:@"LevelNumber"]intValue];
NSLog(@"%i", [[plistDict objectForKey:@"LevelNumber"]intValue]);

私の推測では、pathForResource:ofType:実際にファイルに「Levels.plist.plist」という名前を付けていない限り、NSBundle は呼び出しに対して nil を返していると思います。

そのメソッドがたまたま を返した場合nilでも、残りのコードは続行できることに注意してください。nilファイル パスを指定すると、 はnilNSMutableDictionaryを返し、その後、辞書からオブジェクトを取得するための呼び出しも を返しnilます。したがって、ロギング呼び出しは 0 の出力を示します。

于 2012-07-19T03:13:53.610 に答える
0

私が見つけたのは、この方法は実際のデバイス自体にとって従来のものではないということでした. あなたがする必要があることはここに記載されており、このウェブサイトは実際のデバイスでこれを行う方法を説明しています

于 2012-07-24T19:25:04.627 に答える