【问题标题】:count of objects (0) differs from count of keys (1)对象数 (0) 与键数 (1) 不同
【发布时间】:2013-01-19 21:00:34
【问题描述】:

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

下面的代码是有问题的。

-(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 initWithObjects:forKeys:]: 对象计数 (0) 不同于键计数 (1)'
  • 这意味着您的 plist 已损坏。可能在某处有一个数组元素。
  • 您是否介意指定数组元素的含义,因为据我所知,我真的没有看到任何内容
  • 具体是哪一行引起的错误?如果您无法从堆栈跟踪中找出问题,您可以单步执行以查看失败的位置。
  • 错误是我上面列出的错误,但由于某种原因,代码在这里崩溃 if (newTopScore > [topScores intValue]) { topScores = ([NSString stringWithFormat:@"%i", newTopScore] ); }

标签: objective-c object key plist nsdictionary


【解决方案1】:

一定是这一行:

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)'

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2015-03-18
  • 2021-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-14
  • 2023-03-23
  • 1970-01-01
相关资源
最近更新 更多