【问题标题】:Fetching with an id in Core Data在 Core Data 中使用 id 获取
【发布时间】:2012-09-20 01:58:09
【问题描述】:

我的应用程序中有一个核心数据。其中一个实体是DetailsDetails 有两个名为 guid 的属性,另一个是 details。这两个属性都包含很多值。在获取的时候,我必须取对应guiddetails。我可以使用 guid 获取保存在其他属性中的值吗?如何连接这两个属性?这就是我将值保存到 2 个属性的方式。

ReaderAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];

NSManagedObjectContext *context = [appDelegate managedObjectContext];

NSManagedObject *object;
object = [NSEntityDescription insertNewObjectForEntityForName:@"Details" inManagedObjectContext:context];

[object setValue: [[activity objectForKey:@"category_guid"]stringValue]forKey:@"guid"];
[object setValue:[activity objectForKey:@"details"] forKey:@"details"];

NSError *error;            
if (![context save:&error]) {

    NSLog(@"Error save base");
}
else {

    NSLog(@"saved");                
}

【问题讨论】:

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


    【解决方案1】:

    我不确定我是否理解您的问题,但如果您想基于 guid 选择特定的 Details 对象,您可以创建一个带有 NSPredicateNSFetchRequest,如下所示:

    NSFetchRequest* request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:@"Details" inManagedObjectContext:moc]];
    [request setPredicate:[NSPredicate predicateWithFormat:@"guid == %@", yourGuid]];
    
    NSError *error = nil;
    NSArray *results = [moc executeFetchRequest:request error:&error];
    if([results count] > 0) {
    
        // the object you are looking for
        NSManagedObject* grabbedDetail = [results objectAtIndex:0];
    
        NSString* grabbedDetails = [grabbedDetail valueForKey:@"details"];
    
        // here you have grabbed details attribute
        // I suppose it's of type NSSString... 
    }
    
    // [request release]; if you don't use ARC
    

    关于你的问题,你能解释一下这些是什么意思吗?

    我可以使用 guid 获取保存在其他属性中的值吗? 如何连接这两个属性?

    希望对您有所帮助。

    编辑:

    如果results 为零,您可以先检索没有谓词的对象。因此,请执行以下操作:

    NSFetchRequest* request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:@"Details" inManagedObjectContext:moc]];
    
    NSError *error = nil;
    NSArray *results = [moc executeFetchRequest:request error:&error];
    if([results count] > 0) {
    
        for(NSManagedObject* obj in results) {
    
            NSLog(@"obj -> %@", obj)
        }
    }
    
    // [request release]; if you don't use ARC
    

    如果您没有日志,则表示您没有数据!!相反,使用硬编码的guid 值设置谓词,例如:

    [request setPredicate:[NSPredicate predicateWithFormat:@"guid == %@", @"12345"]];
    

    您需要确保guid 存在。

    我不知道问题是什么,但我使用的查询是正确的,没有详细信息,我无法理解发生了什么。

    干杯。

    【讨论】:

    • 我只是按照你说的那样尝试过。但是 [结果计数] 正在变为 0
    • 提供一些关于您的模型的信息。 guid是什么类型的?
    • 如果查询返回0,则表示没有对象有你指定的guid。首先尝试使用硬编码的guid(确保它存在),看看会发生什么。例如[NSPredicate predicateWithFormat:@"guid == %@", @"12345"];
    • @alpz 删除谓词并打印结果。你能检索任何对象吗?我编辑了答案以适应这个。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-22
    • 2019-12-31
    相关资源
    最近更新 更多