zoukankan      html  css  js  c++  java
  • iOS CoreData relationship 中的inverse

    官方文档建议为每一个可以设置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];


    最近在使用coredata 时 发现了一个inverse的作用:
    比如有 profile 和 score 表,它们之间是1对1关系,我们先建立了一个profile,之后想设置他的score,我们只需要调用 score.profile = profile 或者 profile.score = score 即可,
    不需要2者同时调用,就可以建立起他们的关联。比如我们掉用了
    score.profile = profile 那么 对应profile 的score属性会自动设置!
  • 相关阅读:
    Petapoco 数据库操作类
    .net Cookie操作公共方法 CookieHelper
    .net 服务端缓存 Cache/CacheHelper
    Base64加密解密方法
    对多字段进行去重 ( Linq 方式 )
    BootStrap之 提示工具(Tooltip)插件
    bootstrap之弹出框
    Jquery 强大的表单验证操作
    强大的数据库工具 dbForge Studio ForMySql
    My操作小技巧
  • 原文地址:https://www.cnblogs.com/breezemist/p/4473408.html
Copyright © 2011-2022 走看看