我有一個核心數據問題。我有一個名爲「Group」的實體,以及其他名爲「Contact」的實體。這些實體之間存在「多對多」的關係,因爲一個組可能有許多聯繫人(該組的成員),並且聯繫人可能有許多組(成爲多個組的成員)。核心數據不會覆蓋對象
所以,這是關係:
集團< < ----- >>聯繫
我需要的是插塞觸頭(新的或現有的)作爲現有組的成員。 我的問題是什麼?那麼......如果我創建了一個新的聯繫人,我可以插入它們,但如果聯繫人已經存在,Core Data不會覆蓋並保存它。
這裏是我的代碼:
- (void)saveMemberInGroup:(Message *)message
{
GroupInfo *groupInfo = message.group;
UserInfo *member = message.user;
AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = [app managedObjectContext];
NSError *error;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:CONTACT_ENTITY
inManagedObjectContext:context];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"ident == %@", [member ident]]];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
//Here I check if the contact exists.
Contact *contact;
if ([fetchedObjects count] == 0) {
contact = [NSEntityDescription insertNewObjectForEntityForName:CONTACT_ENTITY
inManagedObjectContext:context];
[contact setIdent:[NSString stringWithFormat:@"%@", [member ident]]];
} else {
contact = [fetchedObjects objectAtIndex:0];
}
//Now I make a new request for the group.
fetchRequest = [[NSFetchRequest alloc] init];
entity = [NSEntityDescription entityForName:GROUP_ENTITY
inManagedObjectContext:context];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"ident == %@", [groupInfo ident]]];
[fetchRequest setEntity:entity];
fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
Group *group = [fetchedObjects objectAtIndex:0];
//Now, I overwrite the group and the contact.
[[group members]addObject:contact];
[[contact memberGroups]addObject:group];
[context save:&error];
}
這裏是我的集團法人:
@interface Group : NSManagedObject
@property (nonatomic, retain) NSString *ident;
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSMutableSet *members;
@end
和我聯繫實體:
@interface Contact : NSManagedObject
@property (nonatomic, retain) NSString *ident;
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSMutableSet *memberGroups;
@end
注:
這真的很奇怪......當我檢查是否已成功更新對象時,一切似乎都沒有問題,組和聯繫人都正確更新了NSSet,但是當我重新啓動應用程序時(我的意思是,最終確定並重新啓動它,或者按XCode中的「play」),Core Data只保存了與創建的新聯繫人的關係!!
實施例:
- 創建Contact1並保存在組1。
- 創建聯繫人2並保存到組1中。
- 現有聯繫人1並保存在組2中。
- 創建聯繫人3並保存到組2中。
如果我檢查覈心數據時,我的應用程序正在運行,我將在組1(聯繫人1,聯繫人2),並在組2(聯繫人1,聯繫人3)。
然後我重新啓動應用程序並再次檢查覈心數據,現在我已經在Group1(Contact1,Contact2)和Group2(Contact3) !!核心數據已經失去了聯繫人1和聯繫人2之間的關係,並且每次我在組和現有聯繫人之間建立關係時都會發生這種情況。
我在做什麼錯?
非常感謝!
我會推薦mogenerator工具來創建你的類而不是Xcode。 http://rentzsch.github.io/mogenerator/ –
請注意這種自動生成的方法,如'[group addMembersObject:contact];'。在以前的版本中,它們必須被重寫。 – Foriger
@MikePollard:這可能是使用Xcode或mogenerator(我仍然使用Xcode)的口味問題,但您可以將其作爲替代方案提及它是很好的。 –