【问题标题】:How to select specific data in Core Data?如何在 Core Data 中选择特定数据?
【发布时间】:2012-07-03 14:18:04
【问题描述】:

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

谢谢!

【问题讨论】:

  • 请检查正确答案;)

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


【解决方案1】:

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

类似的东西:

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

【讨论】:

    【解决方案2】:
    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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-02
      • 2017-11-02
      • 1970-01-01
      • 2019-07-02
      • 1970-01-01
      • 1970-01-01
      • 2015-02-11
      相关资源
      最近更新 更多