gpt4 book ai didi

iphone - 核心数据: How to check for the presence of Many to Many relationship

转载 作者:行者123 更新时间:2023-12-03 20:24:51 27 4
gpt4 key购买 nike

我有一个“歌曲”实体和一个“标签”实体,它们之间具有多对多关系。一首歌曲可以有多个标签,一个标签可以应用于多首歌曲。

我想检查一首歌曲是否有与其关联的特定标签。如果歌曲有与之关联的标签,我想在表格 View 中显示复选标记。

对于类似的逻辑,在Apple“TaggedLocations”示例代码中,进行以下检查来检查关系是否存在。

if ([event.tags containsObject:tag]) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}

如果数据库中有很多标签,这可能会效率低下,因为这会在内存中获取所有标签。如果我这里有错,请纠正我。

是否有更有效的方法来检查歌曲是否与特定标签关联,而不是检查 Song.Tags?

最佳答案

如果完全没有文档记录的话,这实际上很容易做到。您想要使用具有设置操作的谓词创建提取请求。如果我们假设您的 Tag 模型有一个名为 tagValue 的属性,那么您关心的谓词是“ANY Tags.tagValue == 'footag'”

NSString *tagSearch = @"footag";

// However you get your NSManagedObjectContext. If you use template code, it's from
// the UIApplicationDelegate
NSManagedObjectContext *context = [delegate managedObjectContext];

// Is there no shortcut for this? Maybe not, seems to be per context...
NSEntityDescription *songEntity = [NSEntityDescription entityForName:@"Song" inManagedObjectContext:context];

NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:songEntity];

// The request looks for this a group with the supplied name
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY tags.tagValue == %@", tagSearch];
[request setPredicate:predicate];

NSError *error = nil;
NSArray *results = [context executeFetchRequest:request error:&error];

[request release];

关于iphone - 核心数据: How to check for the presence of Many to Many relationship,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1406565/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com