一个错误不断弹出,表示对象的键数不同,然后程序不断崩溃。
以下代码是令人质疑的问题。
-(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];
答案 0 :(得分:2)
必须是这一行:
NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: topScores, nil] forKeys:[NSArray arrayWithObjects: @"bestScore", nil]];
并且必须是topScores
为nil,这意味着objects数组的大小为0,而keys数组的大小为1。
您需要找出topScores
为零的原因。
例如,尝试运行此代码:
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)'