8

我有一个使用 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 的记录。

谢谢!

4

2 回答 2

16

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

类似的东西:

NSPredicate *predicateID = [NSPredicate predicateWithFormat:@"nameID == %d",-1];
[fetchRequest setPredicate:predicateID];
于 2012-07-03T07:09:58.027 回答
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);
}
于 2012-07-03T07:10:12.070 回答