如何为我的核心数据实体建模? [英] How to model my Core Data entity?
问题描述
我想在核心数据中存储 NoteObjects
。通常, NoteObject
具有 NSString * mainText
和 NSMutableArray * arrayOfTags
( NSStrings
的数组)。我现在想使用Core Data,但是数组对于Core Data是一件棘手的事情。通常, NoteObject
数组中的标签数量不能超过50个。那么我应该如何建模呢?我有两个选择:
I want to store NoteObjects
in Core Data. Normally, a NoteObject
has a NSString *mainText
and an NSMutableArray *arrayOfTags
(an array of NSStrings
). I want to now use Core Data, but arrays are a tricky matter with core data. Typically a NoteObject
won't have more than 50 tags in its array. So how should I model this? I have two options:
- 使用
transformable
属性存储数组 - 使用多对多关系,我读过的是更合法的方式。
- Use a
transformable
property to store the array - Use a to-many relationship, which I've read is the more "legit" way to do it.
我应该使用哪个?为什么?以及如何使用简单的结构实现一对多关系?我似乎没办法围绕这个概念。
Which one should I use and why? And how would I implement a to-many relationship with my simple structure? I can't seem to wrap my fingers around that concept.
推荐答案
使用多对多关系。因为在获取请求期间它变得更好,更轻松。请参见下面的屏幕截图。注意右侧的关系管理器,将 NoteObject中的一对多关系设置为标记。忽略播放器实体。
Use to-many relationship. Because it's way better and easier during fetch requests. See the screenshots below. Pay attention to the Relationship manager on the right side, set "To-Many Relationship" from your NoteObject to Tags. Ignore the Player entity.
哦,请注意删除规则。您可能要删除与给定NoteObject关联的所有标签。因此,在这种情况下,请将其设置为Cascade。
Oh and pay attention to the "Delete Rule". You might want to delete all the tags associated with a given NoteObject. So set it to Cascade in that case.
NoteObject实体
NoteObject entity
标签实体
-编辑:
要添加多个标签,您需要首先获取NoteObject-I假设将使用某种ID参数来区分NoteObjects。 CoreData将自动生成标签的添加/删除方法。您将需要使用与以下代码相似的代码:
To add multiple tags you need to first fetch your NoteObject - I assume there will be some sort of ID parameter which you'll use to distinguish NoteObjects. CoreData will automatically generate the add/remove methods for Tags. You'll need to use code similar to the one below:
- (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];
}
这篇关于如何为我的核心数据实体建模?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!