在我的应用程序中,标签和链接之间存在多对多关系,如下所示:
Tags <<-->> Links
我正在尝试返回与具有当前活动标签但未包含在活动标签中的链接相关的标签列表。
我还想获得具有“其他”标签的链接数量的计数,这需要受到活动标签的限制。
使用以下内容,我已经能够返回“其他”标签和链接计数,但返回的计数是每个标签的所有链接。
我希望能够使用与我用来构建子查询的方法类似的方法来计算链接,但我正在努力让它工作。我曾尝试使用计数 NSExpression 中生成的子查询,但是在评估子查询时会出现此错误。
// Test array of tag names
self.activeTagArray = [@[@"tag1", @"tag2"] mutableCopy];
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:[Tag entityName]];
// We want to exclude the tags that are already active
NSPredicate *activeTagsPredicate = [NSPredicate predicateWithFormat:@"NOT ANY name IN %@", self.activeTagArray];
// Build subquery string to identify links that have all of the active tags in their tag set
NSString __block *subquery = @"SUBQUERY(links, $link, ";
[self.activeTagArray enumerateObjectsUsingBlock:^(id tagName, NSUInteger index, BOOL *stop) {
if (index == self.activeTagArray.count - 1) {
subquery = [subquery stringByAppendingString:[NSString stringWithFormat:@"SUBQUERY($link.tags, $tag, $tag.name = '%@') != NULL", tagName]];
} else {
subquery = [subquery stringByAppendingString:[NSString stringWithFormat:@"SUBQUERY($link.tags, $tag, $tag.name = '%@') != NULL AND ", tagName]];
}
}];
subquery = [subquery stringByAppendingString:@") != NULL"];
NSLog(@"Subquery : %@", subquery);
NSPredicate *noTagsPredicate = [NSPredicate predicateWithFormat:subquery];
// Create a predicate array
NSArray *predicateArray = @[noTagsPredicate, activeTagsPredicate, userPredicate];
NSPredicate *compoundPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:predicateArray];
fetchRequest.predicate = compoundPredicate;
fetchRequest.relationshipKeyPathsForPrefetching = @[@"links"];
// Set up the count expression
NSExpression *countExpression = [NSExpression expressionForFunction: @"count:" arguments:@[[NSExpression expressionForKeyPath: @"links.href"]]];
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
expressionDescription.name = @"counter";
expressionDescription.expression = countExpression;
expressionDescription.expressionResultType = NSInteger32AttributeType;
fetchRequest.propertiesToFetch = @[@"name", expressionDescription];
// Sort by the tag name
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
fetchRequest.sortDescriptors = @[sortDescriptor];
fetchRequest.resultType = NSDictionaryResultType;
NSError *error = nil;
NSArray *resultsArray = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (error) {
NSLog(@"Error : %@", [error localizedDescription]);
}
NSMutableArray *allTags = [[NSMutableArray alloc] init];
for (NSDictionary *tagDict in resultsArray) {
NSLog(@"Tag name : %@, Link Count : %@", tagDict[@"name"], tagDict[@"counter"]);
[allTags addObject:tagDict[@"name"]];
}
[allTags addObjectsFromArray:self.activeTagArray];
对此的任何帮助将不胜感激!