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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11306015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 00:45:52  来源:igfitidea点击:

How to select specific data in Core Data?

iphoneobjective-ciosxcodecore-data

提问by kimbebot

I have a sample program that use Core Data and load an sqlite database in it. And I am displaying all the values using this code

我有一个使用 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);
}

This code works fine, my problem here is that I can't select a specific data/record. Example I want to select the record with the ID = 1.

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

Thanks!

谢谢!

回答by Pierre

You have to use predicates (with NSPredicate) before your request execution.

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

Something like that :

类似的东西:

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

回答by Janak Nirmal

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);
}