我有一个tableView,如果此实体属性之一等于字符串,则应该仅显示coreData-entity的对象。

有一个名为Buy的实体,其中一个属性是名为position的字符串

在我的tableViewController代码中是:

@property (strong) NSMutableArray *buy;

- (NSManagedObjectContext *)managedObjectContext
{
    NSManagedObjectContext *context = nil;
    id delegate = [[UIApplication sharedApplication] delegate];
    if ([delegate performSelector:@selector(managedObjectContext)]) {
        context = [delegate managedObjectContext];
    }
    return context;
}

    - (void)viewDidAppear:(BOOL)animated
    {
        [super viewDidAppear:animated];
        NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Buy"];
            self.buy= [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];

        [self.tableView reloadData];
    }


现在,我尝试仅显示包含位置字符串等于“ a”的Buy对象。但是我不怎么写if条件。

预先感谢您的回答。

最佳答案

请执行下列操作 :-

NSString *str="a";
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"position == %@",str];


因此,viewDidAppear函数变为:-

- (void)viewDidAppear:(BOOL)animated
    {
        [super viewDidAppear:animated];
        NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
        NSString *str="a";
        NSPredicate *predicate=[NSPredicate predicateWithFormat:@"position == %@",str];
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Buy"];
        [fetchRequest setPredicate : predicate ];
            self.buy= [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];

        [self.tableView reloadData];
    }

09-27 15:29