使用多對多關係。因爲在獲取請求期間它更好,更輕鬆。請參閱下面的截圖。注意右側的關係管理器,將NoteObject中的「To-Many關係」設置爲標記。忽略播放器實體。
哦,要注意「刪除規則」。您可能希望刪除與給定NoteObject關聯的所有標籤。所以在這種情況下將它設置爲Cascade。
NoteObject實體![enter image description here](https://i.stack.imgur.com/24UBT.png)
標籤實體![enter image description here](https://i.stack.imgur.com/WdFW3.png)
- 編輯:
要添加您需要首先獲取你的NoteObject多個標籤 - 我認爲會有某種形式的ID參數,你將用於區分NoteObjects。 CoreData將自動生成標籤的添加/刪除方法。你需要使用類似的代碼下面的一個:
- (void)addTags:(NSArray *)tags toNoteObjectWithID:(NSString *)noteID {
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"NoteObject"];
NSPredicate *pred = [NSPredicate predicateWithFormat:@"noteID == %@", noteID];
[fetchRequest setPredicate:pred];
NoteObject *noteObject = [[[self managedObjectContext] executeFetchRequest:fetchRequest error:nil] lastObject];
for (NSString *tag in tags) {
Tag *t = [NSEntityDescription insertNewObjectForEntityForName:@"Tag"
inManagedObjectContext:[self managedObjectContext]];
t.body = tag;
t.noteObject = noteObject;
[noteObject addTagsObject:t];
}
[self saveContext];
}
你確定CoreData是正確的方法 - 如果你的數據足夠小,你看看NSCoding嗎?如果你有一個大的數據集,然後按照@Eugene的答案:) – deanWombourne 2012-03-15 18:47:46