实体不是密钥的密钥值编码兼容

dan*_*mer 7 cocoa core-data objective-c

    if (win) {
    // Game was won, set completed in puzzle and time
    // Calculate seconds taken
    int timeTaken = (int)([NSDate timeIntervalSinceReferenceDate] - self.gameStartTime);
    int bestTime = [[self.puzzle valueForKey:@"bestTime"] intValue];
    if (timeTaken < bestTime && bestTime != 0) {
        [self.puzzle setValue:[NSNumber numberWithInt:timeTaken] forKey:@"bestTime"];
        NSLog(@"Best time for %@ is %@", [self.puzzle valueForKey:@"name"], [self.puzzle valueForKey:@"bestTime"]);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我正在制作的iPad游戏中的一些代码,我正在使用Core Data来存储关卡.当一个关卡完成并获胜后,我想为该关卡设置最佳时间.计算所花费的时间,如果它比之前的最佳时间更好,我想将其设置为该级别的最佳时间.

当这个代码尝试从self.puzzle(Core Data中的NSManagedObject)中检索最佳时间时,此代码在'int bestTime'行上失败.最佳时间存储为Core Data模型中的Integer 32.它因SIGABRT错误而失败.

'[<NSManagedObject 0x95334d0> valueForUndefinedKey:]: the entity Puzzle is not key value coding-compliant for the key "bestTime".'
Run Code Online (Sandbox Code Playgroud)

我在网上搜索了为什么会发生这种情况以及如何解决它的原因,但似乎没有任何帮助.还有其他地方可以从Core Data模型访问Integer值,它们可以很好地工作,尽管它们用于过滤和排序查询.

我也不知道我设置值的行是否有效.

任何有关这方面的帮助将不胜感激.

编辑:这是获取一系列谜题的代码,其中一个被认为是上面的谜题.

// Define our table/entity to use  
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Puzzle" inManagedObjectContext:managedObjectContext];   

// Setup the fetch request  
NSFetchRequest *request = [[NSFetchRequest alloc] init];  
[request setEntity:entity];   

// Set the filter for just the difficulty we want
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"difficulty == %d", difficulty];
[request setPredicate:predicate];

// Define how we will sort the records  
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"sortid" ascending:YES];  
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];  
[request setSortDescriptors:sortDescriptors];  
[sortDescriptor release];

// Fetch the records and handle an error  
NSError *error;  
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
Run Code Online (Sandbox Code Playgroud)

dan*_*mer 14

Ok, Firstly, I would like to thank everyone who suggested ideas. They may not have helped me solve the problem, but I learnt more about Core Data and it is always good to find out what I should be checking when things don't work.

我真的不知道问题是什么.直到今天早上,我认为Xcode打开了大约5天,昨天我将属性"bestTime"添加到数据模型中.我只能假设在5天内,Xcode变得有点不稳定,并认为它没有被保存.我已经检查过我已经保存了模型属性,事实上我必须检查3到4次以及我做出任何更改后按下Command + S的习惯.

无论如何,我今天早些时候重新启动了我的机器,当我几分钟前启动Xcode时,我意识到'bestTime'不在模型文件中.我添加了它,重置iPad模拟器上的设置,它工作.

再次感谢大家的帮助,对不起解决方案不是更有趣和基于代码.虽然这让我感觉更好,但我的代码不是原因.


Pet*_*sey 12

该托管对象没有名为" bestTime" 的属性.根据异常消息,它肯定是一个Puzzle,所以你没有声明bestTime你的模型中命名的属性(或者你拼错了它或者以不同的方式大写它).