objective-c - 对象数 (0) 与键数 (1) 不同

标签 objective-c object key plist nsdictionary

不断弹出错误,表示键的数量与对象的数量不同,并且程序不断崩溃。

下面的代码是有问题的。

-(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];

最佳答案

一定是这一行:

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

而且 topScores 一定是 nil,这意味着对象数组的大小为 0,而键数组的大小为 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)'

关于objective-c - 对象数 (0) 与键数 (1) 不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14418801/

相关文章:

ios - 在 iOS 7 中使用 applicationDidEnterBackground : 应用程序进入后台时无法更新 View

java - 某些代码有问题...?

javascript - 多个对象具有相同的键

objective-c - 函数调用而不是 self 消息传递——什么时候使用什么?

objective-c - NSSpellchecker 和 UITextChecker 之间的区别

iphone - 将 NSURLCredentialStorage 与同步 NSURLConnection 结合使用

java - Sentinel 问题与循环允许在 java 中输入 quit 来结束程序

javascript - 在循环中创建的 anchor 标记上绑定(bind)一个带有对象作为参数的 onclick 函数

python - 在 python 中使用 for 循环是一种正确的编程技术来创建对象吗?

key - AHK 长按替代键