gpt4 book ai didi

iphone - 使用多个谓词获取请求?

转载 作者:行者123 更新时间:2023-11-28 20:36:53 26 4
gpt4 key购买 nike

我有一个实体 Tags,我想执行一次提取以获取所有 Tags 并将其分配给 NSFetchedResultsController。但是,我希望获取结果中的第一个对象是 TagtagName 属性等于 "All",然后其余对象按按字母顺序。目前我正在这样做,它只按字母顺序返回所有标签,但我希望名为 "All" 的标签总是第一个,然后按字母顺序返回其余标签。

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"Tag" inManagedObjectContext:appDelegate.managedObjectContext];

[fetchRequest setEntity:entity];
NSSortDescriptor *lastDescriptor =
[[[NSSortDescriptor alloc] initWithKey:@"tagName"ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)] autorelease];

[fetchRequest setSortDescriptors:[NSArray arrayWithObject:lastDescriptor]];

最佳答案

您需要使用自己创建的比较器,而不是默认的比较器,因此您可以这样做:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"Tag" inManagedObjectContext:appDelegate.managedObjectContext];

[fetchRequest setEntity:entity];
NSSortDescriptor *lastDescriptor =
[[[NSSortDescriptor alloc] initWithKey:@"tagName" ascending:YES comparator:^NSComparisonResult(NSString* tag1, NSString* tag2) {

if ([tag1 isEqualToString:@"All"]) return NSOrderedAscending;
if ([tag2 isEqualToString:@"All"]) return NSOrderedDescending;

return [tag1 compare:tag2];
}] autorelease];

[fetchRequest setSortDescriptors:[NSArray arrayWithObject:lastDescriptor]];

编辑

就像@Andrew Madsen 告诉您可以使用比较器一样,我看不出他已经回答了您的问题。

你也可以使用一个选择器,只需要在你的模型中实现它一个方法来进行比较,我犯了一个错误并相信那是你正在做的,来自苹果文档:

selector

The method to use when comparing the properties of objects, for example caseInsensitiveCompare: or localizedCompare:. The selector must specify a method implemented by the value of the property identified by keyPath. The selector used for the comparison is passed a single parameter, the object to compare against self, and must return the appropriate NSComparisonResult constant. The selector must have the same method signature as: - (NSComparisonResult)localizedCompare:(NSString *)aString

关于iphone - 使用多个谓词获取请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10091536/

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