【问题标题】:How do I filter my array to display only specific category items?如何过滤我的数组以仅显示特定类别项目?
【发布时间】:2014-08-15 03:18:34
【问题描述】:

此代码当前列出了我的所有类别。但是,我想过滤此结果以显示特定结果。例如... 该数组包含牙买加、日本、德国和亚洲项目。我想过滤显示的结果,只显示日本和德国。我读过 NSPredicate 可以帮助我,但我不太确定如何在这里实现它。

数据控制器.M

+(NSArray*) getCategories {

AppDelegate* delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
NSManagedObjectContext* context = delegate.managedObjectContext;

NSError *error;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setReturnsObjectsAsFaults:NO];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"StoreCategory" inManagedObjectContext:context];


NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"created_at" ascending:YES];
[fetchRequest setSortDescriptors:@[sortDescriptor]];

[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];

return fetchedObjects;
}

类别.m

   -(UITableViewCell*)MGListView:(MGListView *)listView1 didCreateCell:(MGListCell *)cell indexPath:(NSIndexPath *)indexPath {

    if(cell != nil) {

    StoreCategory* cat = [listViewMain.arrayData objectAtIndex:indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor clearColor];

    [cell.labelTitle setText:cat.category];
    [self setImage:cat.category_icon imageView:cell.imgViewThumb];


}

return cell;
}

【问题讨论】:

    标签: nsmutablearray nsarray nspredicate


    【解决方案1】:

    您无法在此方法中过滤不需要的类别,因为indexPath 将是一个索引序列。

    在调用 UITableView 委托或 DataSource 函数之前,您必须构建另一个包含所需类别的数组,例如在 ViewDidLoad 中。

    【讨论】:

      【解决方案2】:

      这种方法似乎可以解决问题。

      NSPredicate *predicate = [NSPredicate predicateWithFormat:@"category CONTAINS[cd] %@ OR category CONTAINS[cd] %@", @"Japan", @"Germany", context];
      [fetchRequest setPredicate:predicate];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-04-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-18
        • 1970-01-01
        相关资源
        最近更新 更多