如何在Core Data中选择特定数据?

时间:2012-07-03 07:04:53

标签: iphone objective-c ios xcode core-data

我有一个使用Core Data并在其中加载sqlite数据库的示例程序。我正在使用此代码显示所有值

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Name"
                                          inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];

for (Name *name in fetchedObjects) {
    NSLog(@"ID: %@", name.nameId);
    NSLog(@"First Name: %@", name.first);
    NSLog(@"Middle Name: %@", name.middle);
    NSLog(@"Last Name: %@", name.last);
}

这段代码工作正常,我的问题是我无法选择特定的数据/记录。示例我想选择ID = 1的记录。

谢谢!

2 个答案:

答案 0 :(得分:16)

在执行请求之前,您必须使用谓词(使用NSPredicate)。

类似的东西:

NSPredicate *predicateID = [NSPredicate predicateWithFormat:@"nameID == %d",-1];
[fetchRequest setPredicate:predicateID];

答案 1 :(得分:10)

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Name"
                                          inManagedObjectContext:context];
[fetchRequest setEntity:entity];

//Add following method to your code. this will help you to get desired result.
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"yourColumnID == %@", yourID]];

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

for (Name *name in fetchedObjects) {
    NSLog(@"ID: %@", name.nameId);
    NSLog(@"First Name: %@", name.first);
    NSLog(@"Middle Name: %@", name.middle);
    NSLog(@"Last Name: %@", name.last);
}