核心数据错误:'订购多对多关系的价值不可接受的类型'

时间:2014-06-02 01:26:28

标签: ios core-data

我是使用Core Data for iOS的初学者。我试图在这里创建一个库函数,但是我收到了这条消息:

'NSInvalidArgumentException', reason: 
    'Unacceptable type of value for ordered to-many relationship: property 
    = "studenthistory"; desired type = NSOrderedSet; given type = __NSSetI; 
    value = {(
      <NSManagedObject: 0x8cacd20> (entity: StudentHistory; id: 0x8cacd80 
      <x-coredata:///StudentHistory/tE710FEAD-C78E-4C91-8F38-23BDC5AA2C943> ; 
      data: {
        bookid = 5;
        checkin = 6;
        checkout = 7;
        open = TBA;
        student = nil;

关系是学生 - &gt; (对很多人) - &gt; StudentHistory。

我只能猜测,但我怀疑问题正在发生,试图设置一个对象,而期望更多,因为它是NSSet

以下是代码:

...
StudentHistory *stuhist = [NSEntityDescription insertNewObjectForEntityForName:@"StudentHistory" inManagedObjectContext:self.managedObjectContext];

stuhist.bookid = _bookidTextField.text;
stuhist.checkout = _checkoutTextField.text;
stuhist.checkin = _checkinTextField.text;
stuhist.open = @"TBA";

newStu.studenthistory = [NSSet setWithObject:stuhist];
newStu.studenthistory = [NSSet setWithObject:stuhist];


NSError *error = nil;
if (![self.managedObjectContext save:&error]) {
    NSLog(@"UH OH! Couldn't save: %@", [error localizedDescription]);
}

[self.navigationController popViewControllerAnimated:YES];

1 个答案:

答案 0 :(得分:5)

错误信息非常明确:您已经定义了#34; studenthistory&#34;作为订购到多个 关系,因此必须为其分配NSOrderedSet

newStu.studenthistory = [NSOrderedSet orderedSetWithObject:stuhist];

或者,设置反向关系

stuhist.student = newStu;

(请注意,有序关系的自动生成的访问器方法 还有虫子。有关问题和解决方法的说明,请参阅 Exception thrown in NSOrderedSet generated accessors。)