开发者

CoreData inverse question

开发者 https://www.devze.com 2023-04-07 19:31 出处:网络
My understanding of an inverse relationship in CoreData is that these two statements should be equivalent:

My understanding of an inverse relationship in CoreData is that these two statements should be equivalent:

[department addEmployee:employee];开发者_C百科
[employee setDepartment:department];

and that you only need to do one of them.

However, if I do this:

[department addEmployee:employee];
NSLog(@"%@",[employee department]);

It doesn't appear the the relationship was updated correctly.

Doing it this way however, works fine:

[employee setDepartment:department];
NSLog(@"%@",[employee department]);

I've also tried calling "processPendingChanges" on the context before the NSLog but it doesn't make a difference


Something looks wrong about your code. You have a method addEmployee, but the usual naming convention for such a method would be addEmployeesObject. It has an awkward name because you usually specify the name of a to-many relationship like that as "employees". Key-Value coding knows how to change the capitalization of your property name, but it doesn't know how to unpluralize it.

If you are calling addEmployee and not getting an error, either you have done something in an unconventional way, or you might be calling some unrelated method that happens to exist. If it's the latter it could explain your problem.

My second guess is to check to make sure your inverse is defined in both directions. That is, Department should have an employees relationship, and its inverse should be specified as department. Employee should have a department relationship, and its inverse should be specified as employees. I think if you use the model editor in XCode it automatically sets both inverses if you set one, but it might be possible to unintentionally override that, and I imagine if you define your data model in code you could do it.

Otherwise it seems that what you are doing should work.


Check your NSManagedObject subclasses (the classes that represent the classes in your Core Data model) that the relationships match what you have in your data model. For example, if you added a relationship to the model after you already generated/coded your Employee and Department NSManagedObject subclasses, then those subclasses will be out of date and not reflect your model.

0

精彩评论

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

关注公众号