从数据库中获取特定谓词

时间:2011-08-12 06:53:11

标签: ios core-data nspredicate nsfetchrequest

我有4个CoreData数据库。每个人实际上都有自己的价值。但它太重了,我想把它减少到1个数据库。因此,每次我想从数据库中提取信息时,我都可以选择要提取的内容。我需要使用NSPredicate来设置我想拉izzit的字符串吗?

我是否设置了这样的NSPredicate?

NSString *value = @"Food";
NSString *wildcardedString = [NSString stringWithFormat:@"%@*", value];
[[NSPredicate predicateWithFormat:@"ANY places.type like %@", wildcardedString];

如何将NSPredicate与获取请求序列绑定?

这是我的fetchedResultsController

- (NSFetchedResultsController *)fetchedResultsController {
    if (fetchedResultsController != nil) 
    {
        return fetchedResultsController;
    }

    CoreDataMelakaAppDelegate *appDelegate = (CoreDataMelakaAppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *context = [appDelegate managedObjectContext];
    NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease];
    [fetchRequest setEntity:[NSEntityDescription entityForName:@"WhereTo" inManagedObjectContext:context]];
    NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES] autorelease];
    NSArray *sortDescriptors = [[[NSArray alloc] initWithObjects:sortDescriptor, nil] autorelease];
    [fetchRequest setSortDescriptors:sortDescriptors];
   // NSPredicate *pred = [NSPredicate predicateWithFormat:@"(name = %@)", wher.name];
    //[fetchRequest setPredicate:pred];
    NSString *value = @"Nasi";
    NSString *wildcardedString = [NSString stringWithFormat:@"%@*", value];
    [[NSPredicate predicateWithFormat:@"ANY wher.name like %@", wildcardedString];
    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:context sectionNameKeyPath:nil cacheName:@"Root"];
    aFetchedResultsController.delegate = self;
    self.fetchedResultsController = aFetchedResultsController;
    [aFetchedResultsController release];
    return fetchedResultsController;
}  

1 个答案:

答案 0 :(得分:1)

当您更改获取的结果控制器(FRC)使用的获取请求的谓词时,您必须创建一个新的获取结果控制器。

您的代码在逻辑上很好但它只使用编译为的谓词创建一次FRC:

ANY wher.name like Nasi*

...每次FRC执行其提取时,它都会使用该确切谓词。

如果要使用灵活谓词,则每次更改谓词时都需要创建新的FRC。