'NSInvalidArgumentException',原因:'to-many关系的值不可接受的类型:property =“detail”;

时间:2014-07-14 11:06:58

标签: objective-c core-data

这是我的数据模型:

enter image description here

这是我的代码:

NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *failedBankInfo = [NSEntityDescription insertNewObjectForEntityForName:@"FailedBankInfo" inManagedObjectContext:context];
[failedBankInfo setValue:@"Test Bank" forKeyPath:@"name"];
[failedBankInfo setValue:@"Testville" forKeyPath:@"city"];
[failedBankInfo setValue:@"Testland" forKeyPath:@"state"];

NSManagedObject *failedBankDetails = [NSEntityDescription insertNewObjectForEntityForName:@"FailedBankDetail" inManagedObjectContext:context];
[failedBankDetails setValue:[NSDate date] forKey:@"closeDate"];
[failedBankDetails setValue:[NSDate date] forKey:@"updateDate"];
[failedBankDetails setValue:[NSNumber numberWithInt:12345] forKey:@"zip"];
[failedBankDetails setValue:failedBankInfo forKeyPath:@"info"];
[failedBankInfo setValue:failedBankDetails forKey:@"detail"];

NSError *error;
if(![context save:&error]) {
    NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"FailedBankInfo" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *info in fetchedObjects) {
    NSLog(@"Name: %@", [info valueForKey:@"name"]);
    NSManagedObject *details = [info valueForKey:@"details"];
    NSLog(@"Zip: %@", [details valueForKey:@"zip"]);
}

以下是跟踪日志:

2014-07-14 14:56:57.080 FailedBankCD[87194:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unacceptable type of value for to-many relationship: property = "detail"; desired type = NSSet; given type = NSManagedObject; value = <NSManagedObject: 0x8c452d0> (entity: FailedBankDetail; id: 0x8c63740 <x-coredata:///FailedBankDetail/t5A5AD25D-C89A-4FA2-A776-C91A3F0413083> ; data: {
    closeDate = "2014-07-14 10:56:55 +0000";
    info = "0x8c60b40 <x-coredata:///FailedBankInfo/t5A5AD25D-C89A-4FA2-A776-C91A3F0413082>";
    updateDate = "2014-07-14 10:56:55 +0000";
    zip = 12345;
}).'
*** First throw call stack:
(

错误发生在该行:

[failedBankInfo setValue:failedBankDetails forKey:@"detail"];

问题的原因是什么?我该如何解决?

2 个答案:

答案 0 :(得分:0)

那么,我会更清楚地说明这一点:

而不是

[failedBankInfo setValue:failedBankDetails forKey:@"detail"];

使用

[failedBankInfo addDetail:failedBankDetails];

让魔法发生。 关键是,你确实有一对多,由一个集合表示。因此,不要使用单个托管对象覆盖该集合,而是添加它。

答案 1 :(得分:0)

只需查看NSManagedObject的头文件即可。您的FailedBankInfo类与FailedBankDetail具有多对多关系。这意味着1 FailedBankInfo可以有许多FailedBankDetail对象引用,并暗示细节关系是NSSet。逆是一对一的关系,所以它是一个简单的FailedBankDetail对象。你的问题在于这一行:

[failedBankInfo setValue:failedBankDetails forKey:@"detail"];

你需要分配一个NSSet(FailedBankDetail对象,即使它是一组1个对象)。在FailedBankInfo的标题中定义了便利方法,这使得这很容易。