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

use*_*951 1 core-data ios

我是初学者,正在使用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;
Run Code Online (Sandbox Code Playgroud)

关系是学生 - >(对许多人) - > 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];
Run Code Online (Sandbox Code Playgroud)

Mar*_*n R 5

错误信息非常明确:您已将"studenthistory"定义为有序的多对多关系,因此必须为其分配NSOrderedSet:

newStu.studenthistory = [NSOrderedSet orderedSetWithObject:stuhist];
Run Code Online (Sandbox Code Playgroud)

或者,设置反比关系:

stuhist.student = newStu;
Run Code Online (Sandbox Code Playgroud)

(请注意,有序关系的自动生成的访问器方法仍然存在错误.有关问题和解决方法的说明,请参阅 NSOrderedSet生成的访问器中抛出的异常.)