2

キーの数とオブジェクトの数が異なるというエラーが表示され続け、プログラムがクラッシュし続けます。

以下のコードは、問題とされているものです。

-(void)saveData //error is in here
{

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//get documents path
NSString *documentsPath = [paths objectAtIndex:0];
//get the path to our Data/plist file
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"Data.plist"];

//set the variables to the values in the text fields
self.topScores = highScore.text;

//create dictionary with values in UITextFields
NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: topScores, nil] forKeys:[NSArray arrayWithObjects: @"bestScore", nil]];

NSString *error = nil;
//create NSData from dictionary
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList: plistDict format: NSPropertyListXMLFormat_v1_0 errorDescription: &error];

//check if plist data exists
if (plistData)
{
    //write plistData to our Data.plist file
    [plistData writeToFile:plistPath atomically:YES];
}
else
{
    NSLog(@"Error in saveData: %@", error);
    [error release];
 }
}

コードは機能しますが、ここでクラッシュします

         if (newTopScore > [topScores intValue]) 
        {
            topScores = ([NSString stringWithFormat:@"%i", newTopScore]); 
        }

        highScore.alpha = 1; 

    [self saveData];
4

1 に答える 1

2

次の行である必要があります。

NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: topScores, nil] forKeys:[NSArray arrayWithObjects: @"bestScore", nil]];

nilでなければなりません。topScoresつまり、オブジェクト配列のサイズは 0 で、キー配列のサイズは 1 です。

topScoresなぜnilなのかを調べる必要があります。

たとえば、次のコードを実行してみてください。

NSDictionary *plistDict = [NSDictionary dictionaryWithObjects:@[] 
                                                      forKeys:@[@"bestScore"]];

あなたは得るでしょう:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSDictionary initWithObjects:forKeys:]: count of objects (0) differs from count of keys (1)'

于 2013-01-19T21:31:31.280 に答える