我有一个类似于此网站上的“标签”功能的输入字段:用户输入一堆单词或短语,这些单词或短语显示在自己的气泡中。这些单词/短语与日记条目相关联(基本上标记日记条目),并且在概述页面上我想显示这些单词/短语的前 5 或 10 个。
我最初的实现是在每个日记条目中存储一个字符串,该字符串基本上连接所有这些单词/短语。当我读取数据时,我根据预定义的分隔符分割该字符串。这效果很好,但如果我有很多条目包含相当数量的这些单词/短语,那么找到前 5/10 名将会非常糟糕。更好的方法是什么?
所以,我有这样的东西:
@interface JournalEntry : NSManagedObject
{
@property (nonatomic, retain) NSNumber * entryId;
@property (nonatomic, retain) NSDate * dateCreated;
@property (nonatomic, retain) TagsInfo *tagsInfo;
}
@interface TagsInfo : NSManagedObject
{
@property (nonatomic, retain) JournalEntry * journalEntry;
@property (nonatomic, retain) NSString * tagString;
}
我认为在正常的数据库设置中,我会为标签创建一个表,在其中存储类似 [journalEntryId, tagEntry] 的内容。每个日记条目都会有一堆这样的条目。这应该是类似的吗?
最佳答案
这就是我要做的,创建一个与 JournalEntry
具有多对多关系的新 Tag
实体。将现有的 TagInfo
迁移到 Tag
并更新关系。
标签
至少应具有以下内容:
- 与
JournalEntry
的一对多关系 - 名为
tagString
的字符串(或tagName
或其他)。
JournalEntry
将与 Tag
建立一对多关系。 tagString
将是唯一的,因为每个 Tag
可能与多个日记条目相关。
然后您可以获取标签以及每个标签被使用的次数,如下所示:
NSExpression *tagCountExpression = [NSExpression expressionWithFormat:@"count(journalEntries)"];
NSExpressionDescription *tagCountExprDescription = [[NSExpressionDescription alloc] init];
tagCountExprDescription.name = @"count";
tagCountExprDescription.expression = tagCountExpression;
tagCountExprDescription.expressionResultType = NSInteger64AttributeType;
NSFetchRequest *tagFetch = [NSFetchRequest fetchRequestWithEntityName:@"Tag"];
[tagFetch setResultType:NSDictionaryResultType];
tagFetch.propertiesToFetch = @[ @"tagString", tagCountExprDescription ];
tagFetch.propertiesToGroupBy = @[ @"tagString" ];
这将为您提供一系列字典。每个都包含一个 tagString
和一个 count
,表示该标签有多少相关的日记条目。您必须自己对其进行排序(不能使用表达式作为排序描述符)。
关于ios - CoreData 和最常使用/标记的词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28100811/