无法从核心数据中获取实体

时间:2014-09-01 11:30:33

标签: ios objective-c iphone core-data

我使用以下代码行从核心数据中获取具有指定ID(theID)的Products类型的对象,尽管每件事看起来都不错,我确信核心数据中存在ID但结果始终为空。

-(Products *) currentTargetInContext:(NSManagedObjectContext *)context withMyId:(NSString *)theID
{
    Products * match;

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName: @"Products" inManagedObjectContext:context];
    [request setEntity:entity];
    [request setReturnsDistinctResults:YES];
    [request setResultType:NSManagedObjectResultType];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"myid == %@", theID];
    [request setPredicate:predicate];

    NSError *error;
    NSArray *objects = [context executeFetchRequest:request error:&error];
    match = nil;
    if (objects == nil)
    {
        // handle the error
    }
    else
    {
        if ([objects count] > 0)
        {
            match = (Products *)[objects firstObject];
        }
    }
    return match;
}

代码中可能出现什么问题?

4 个答案:

答案 0 :(得分:1)

尝试更改NSPredicate代码,只使用单个'='符号。

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"myid = %@", theID];

答案 1 :(得分:0)

使用以下声明:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"myid LIKE[c] %@", theID];

希望这个解决你的问题。

答案 2 :(得分:0)

使用此

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"myid == \"%@\"", theID];

而不是

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"myid == %@", theID];

答案 3 :(得分:-1)

我认为这里可能存在2-3个问题,这可能导致您遇到的这些错误。

首先,我建议您确保检查您的产品实体中是否有您正在搜索的ID的项目,这意味着首先打印所有产品实体行,以便我们确定我们正在搜索正确的内容。

然后第二个你设置managedObjectContext = appDelegate.managedObjectContext 这里appDelegate是AppDelegate类的对象,导入AppDelegate,你在哪个文件中调用这个方法

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
  1. 检查你设置的 theID 的类型,如果它是字符串然后它的好,但一般人们和我也习惯在NSNumber中使用这样的ID,如果它是NSNumber转换你的字符串在NSNumber
  2. 4.检查完所有上述要点后,通过在代码中注明这些行来运行代码

    request setReturnsDistinctResults:YES];
    [request setResultType:NSManagedObjectResultType];
    

    如果所有这些点都无济于事,您可以向我们展示您的productEntity NSManagedObjectClass .h和.m