iOS CoreData relationship 中的inverse

來源:互聯網
上載者:User

標籤:

官方文檔建議為每一個可以設定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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.