需要按类别产品的数量/数量对按提取请求检索的类别列表进行排序。然后,我希望能够手动将几个类别(已过滤掉)添加到数组中,以便它们位于列表的底部。我一直遇到包含KVC聚合的" Keypath的错误,其中不应该是一个......"当我尝试按产品数排序时。
我在这里错过了什么/做错了什么?谢谢!
Category.h
@class Category;
@interface Category : NSManagedObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSSet *products;
@end
Product.h
@class Category;
@interface Product : NSManagedObject
@property (nonatomic, strong) NSString *sku;
@property (nonatomic, strong) NSString *name; // Product name
@property (nonatomic, strong) NSString *prodDescription;
@property (nonatomic, strong) Category *category; // Product category
@property (nonatomic, strong) NSString *upc;
@property (nonatomic, strong) NSString *countryCode;
@property (nonatomic, strong) NSString *webpage;
@property (nonatomic, strong) NSString *manual;
@property (nonatomic, strong) NSString *quickStart;
@property (nonatomic, strong) UIImage *thumb;
@property (nonatomic, strong) NSString *thumbURLString;
@property (nonatomic, strong) UIImage *mainImg;
@property (nonatomic, strong) NSString *mainImgURLString;
@property (nonatomic, strong) UIImage *secondaryImg;
@property (nonatomic, strong) NSString *secondaryImgURLString;
@end
CategoriesViewController.m
- (NSFetchedResultsController *)fetchedResultsController {
if (_fetchedResultsController == nil) {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:[NSEntityDescription entityForName:@"Category" inManagedObjectContext:self.managedObjectContext]]; // Fetch categories
NSArray *sortDescriptors = nil;
NSString *sectionNameKeyPath = nil;
// Sort by number of products in category
sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"category.@count" ascending:NO]];
[fetchRequest setSortDescriptors:sortDescriptors];
// Use predicate to exclude Accessories and Replacement Parts categories from initial array
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name != 'Accessories' AND name != 'Replacement Parts'"];
[fetchRequest setPredicate:predicate];
_fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:sectionNameKeyPath
cacheName:nil];
}
return _fetchedResultsController;
}
答案 0 :(得分:0)
答案 1 :(得分:0)
通常,这可以通过在记录本身中设置计数变量来解决。这允许获取的结果控制器对该计数的值进行排序。我在相关关系的自定义设置器中保留了这种计数。在您的情况下,这可能是products
的集合,新变量可能被称为productCount
。 Xcode有一个片段模板用于此类事情。这是一个例子:
- (void) addProductsObject: (Product *) value {
NSSet *changedObjects = [NSSet setWithObject:value];
[self willChangeValueForKey: kDays withSetMutation: NSKeyValueUnionSetMutation usingObjects: changedObjects];
[[self primitiveValueForKey: kDays] addObject: value];
[self didChangeValueForKey: kDays withSetMutation: NSKeyValueUnionSetMutation usingObjects: changedObjects];
self.productCount = (int32_t)self.products.count;
} // -addProductsObject:
其他三种方法同样简单明了。