我有设备的核心数据模型和数据存储。每个设备包含颜色,存储和价格。无论如何我可以过滤已经获取请求(来自DB的所有设备的数组)。我需要为包含颜色,存储和价格的设备实现过滤功能。过滤器可以多次应用,意味着一旦你为颜色应用过滤器,它只会显示那些包含那些颜色+相应存储的设备,反之亦然。我可以使用谓词过滤一次但是为了应用另一个过滤器我需要再次调用查询以获取所有设备并应用受尊重的过滤器。还有其他方法,所以当我从获取请求中获取过滤数据时,我可以对相同的过滤数据应用其他过滤器。或者我在核心数据中唯一的工作方式。
这就是我根据所选过滤器过滤数据的方式:
-(void)getAllDevicesDetailBasedOnFilter{
NSMutableArray *predicateArray = [NSMutableArray array];
//DevicesCatalogueSkuDetails
isColorSelected = YES;
isBrandSelected = YES;
isStorageSelected = YES;
isPriceSelected = YES;
if (isPriceSelected) {
NSPredicate * pricePredicate = [NSPredicate predicateWithFormat:@"ANY skuDetails.priceWithVat >= %.f AND ANY skuDetails.priceWithVat <= %.f",minimumPriceValue,maximumPriceValue];
[predicateArray addObject:pricePredicate];
}
if (isBrandSelected) {
NSPredicate * brandPredicate = [NSPredicate predicateWithFormat:@"brand = %@", @"Samsung"];
[predicateArray addObject:brandPredicate];
}
if (isColorSelected) {
NSPredicate * colorPredicate = [NSPredicate predicateWithFormat:@"ANY skuDetails.color CONTAINS[cd] %@",@"Green"];
[predicateArray addObject:colorPredicate];
}
if (isStorageSelected) {
NSPredicate * colorPredicate = [NSPredicate predicateWithFormat:@"ANY skuDetails.storage CONTAINS[cd] %@",@"256"];
[predicateArray addObject:colorPredicate];
}
NSPredicate *compoundPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:predicateArray];
[[CoreDataManager sharedInstance] fetchWithEntity:@"DevicesCatalogue" Predicate:compoundPredicate success:^(NSArray *fetchLists) {
if(fetchLists) {
}
}failed:^(NSError *error) {
}];
}
答案 0 :(得分:0)
你可以使用@property NSMutableArray fetchLists;
- (NSPredicate *) getFirstPredicate {
// create your initial predicate here
}
- (NSPredicate *) getSecondPredicate {
// create your second predicate here
}
- (void) fetchEntities {
[[CoreDataManager sharedInstance] fetchWithEntity: @"DevicesCatalogue" predicate: nil
success: ^(NSArray *result) {
if(result) {
self.fetchLists = result;
}
}
failed: ^(NSError *error) {
// handle error
}];
}
[self fetchEntities];
NSArray *firstFilteredArray = [self.fetchLists filteredArrayUsingPredicate: getFirstPredicate];
NSArray *secondFilteredArray = [firstFilteredArray filteredArrayUsingPredicate: getSecondPredicate];
然后从您想要获取和过滤数据的位置执行以下操作:
fetchLists
等
或者使用第一个和第二个谓词的复合来过滤原始new_data <- cats[which(x == unique(x)[1]),]
。