NSManagedObject unrecognized selector sent to inst

2019-08-07 14:49发布

I have a Core Data model as follows, where children is a to-many relationship.

.h

@implementation MyEntity

@dynamic name;
@dynamic children;

@end

.m

@interface MyEntity : NSManagedObject

@property (nonatomic) NSString *name;
@property (nonatomic) NSOrderedSet *children;

@end

I then try to set it using:

        MYAppDelegate *delegate = (MYAppDelegate *)[UIApplication sharedApplication].delegate;
        NSManagedObjectContext *managedObjectContext = [delegate managedObjectContext];
        NSEntityDescription *categoryEntity = [NSEntityDescription entityForName:@"MyEntity" inManagedObjectContext:managedObjectContext];
        NSManagedObject *newCategory = [[NSManagedObject alloc] initWithEntity:categoryEntity insertIntoManagedObjectContext:managedObjectContext];
        [newCategory setValue:key forKey:@"name"];
        NSOrderedSet *testSet = [[NSOrderedSet alloc] initWithArray:@[@"This", @"is", @"a", @"test"]];
        [newCategory setValue:testSet forKey:@"children"];
    }
}

Yet on that last line, I get this error:

NSCFConstantString managedObjectContext]: unrecognized selector sent to instance 0xe8fa0'

If I change NSOrderedSet to NSSet the compiler complains that it expects an NSOrderedSet.

How can I assign the set to the NSManagedObject?

1条回答
成全新的幸福
2楼-- · 2019-08-07 15:40

The problem isn't the NSOrderedSet, its the NSString instances that you put inside the set. These need to be replaces with instances of the entity which is configured in the data model at the destination of the relationship. You can't fill the relationship with the wrong kind of object.

查看更多
登录 后发表回答