码迷,mamicode.com
首页 > 移动开发 > 详细

iOS CoreData relationship 中的inverse

时间:2015-05-03 11:52:18      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

官方文档建议为每一个可以设置inverse的relationship设置一个inverse。目的是保持数据库的正确性。但是没有具体的说明。

我在stackoverflow中找到了一个是分好的答案,http://stackoverflow.com/questions/764125/does-every-core-data-relationship-have-to-have-an-inverse

内容如下:

Apple documentation has an great example that suggest a situation where you might have problems by not having inverse relationship. Lets map it into this case.

Lets Assume you modeled it as follows 技术分享

Note you have to-one relationship called "type", from SocialApp to SocialAppType. The relationship is non-optional and has a "deny" delete rule.

Now Lets consider following Code.

SocialApp *socialApp;
SocialAppType *appType;
// assume entity instances correctly instantiated

[socialApp setSocialAppType:appType];
[managedObjectContext deleteObject:appType];
BOOL saved = [managedObjectContext save:&error];

What we expect is to fail this context save since we have set the delete rule as Deny while relationship is non optional. 

But here the save succeeds.

Reason is we haven‘t set a inverse relationship. Because of that socialApp instance not get marked as changed when appType is deleted. So no validation happens for socialApp before saving (It assumes no validation needed since no change happened). But actually a change happened. But it doesn‘t get reflected. 

if we recall appType by

SocialAppType *appType = [socialApp socialAppType];

appType is nil. 

So weird isn‘t it. get nil for non optional attribute?

So you are in no trouble if you have set up the inverse relationship. Otherwise you have to do force validation by writing the code as follows.

SocialApp *socialApp;
SocialAppType *appType;
// assume entity instances correctly instantiated

[socialApp setSocialAppType:appType];
[managedObjectContext deleteObject:appType];

[socialApp setValue:nil forKey:@"socialAppType"]
BOOL saved = [managedObjectContext save:&error];

iOS CoreData relationship 中的inverse

标签:

原文地址:http://www.cnblogs.com/breezemist/p/4473408.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!