开发者

CoreData: How to handle inheritance dynamically?

开发者 https://www.devze.com 2023-04-08 20:37 出处:网络
e.g., I\'ve 开发者_如何学Cgot three classes in my CoreData-project: Person, Pupil and Teacher. Pupil and Teacher have Person as parent class.

e.g., I've 开发者_如何学Cgot three classes in my CoreData-project: Person, Pupil and Teacher. Pupil and Teacher have Person as parent class.

Now, I'd like to do something like:

Person *person;

if (createPupil) {
    person = [[Pupil alloc] init];
    ...
} else {
    person = [[Teacher alloc] init];
    ...
}

[self.managedObjectContext save:&error];

But it seems like its always saving to the Person-table. When I try to fetch pupils or teachers, they are empty. Is there a possiblity to make this dynamic?

Thanks a lot,

Stefan


Your if statements already introduce the dynamic element. This is how I would do it:

if (createPupil) {
   Pupil *person = [NSEntityDescription 
      insertNewObjectForEntityForName:"Pupil"
      inManagedObjectContext:self.managedObjectContext];
   // ... configure
} 
else {
   Teacher *person = [NSEntityDescription 
      insertNewObjectForEntityForName:"Teacher"
      inManagedObjectContext:self.managedObjectContext];
   // ... configure

}

[self.managedObjectContext save:&error];

Also check out Apple's comment in the insertNewObjectForEntityForName: inManagedObjectContext: documentation.

The method is particularly useful on Mac OS X v10.4, as you can use it to create a new managed object without having to know the class used to represent the entity. This is especially beneficial early in the development life-cycle when classes and class names are volatile.

0

精彩评论

暂无评论...
验证码 换一张
取 消