核心数据获取结果

时间:2009-08-03 16:24:23

标签: iphone objective-c cocoa core-data

使用以下代码我正在创建一个获取请求。我遇到的问题是获取获取请求数据并对其执行某些操作,例如将其放入变量(就像我在下面尝试使用firstManagedObject变量一样)。即,我不明白如何处理我创建的“结果”NSArray(如下面的代码所示),以获得不是“(entity:Question; id:0x10b6250< -coredata:// 90FA9FD7-4CFC-4039-8A0C-40116055CADF / Question / p2; data:fault)“或类似。在我创建的NSLog中(在最后一行),我记录了从executeFetchRequest填充的“result”NSArray(下面以粗体显示),但我不知道如何采取下一步来获取实际的“问题”文本。任何帮助表示赞赏。谢谢。

NSLog结果:

获取请求getQuestionsByParent:2 found(子变量:{     formId =“9822217D-6A55-4475-88EC-E2552B336E1B”;     sectionNumber = 2; },结果:(      (实体:问题; id:0x10a8720 x-coredata:// 90FA9FD7-4CFC-4039-8A0C-40116055CADF / Question / p2; data:fault),      (实体:问题; id:0x1092920 x-coredata:// 90FA9FD7-4CFC-4039-8A0C-40116055CADF / Question / p4; data:fault) ))

代码:

    NSManagedObjectContext *moc_ = [self managedObjectContext];

    NSMutableDictionary *dictionary=[[NSMutableDictionary alloc]init];
    [dictionary setObject:section.ordinal forKey:@"sectionNumber"];
    [dictionary setObject:section.parent.id forKey:@"formId"];

    NSError *error = nil;    
    NSManagedObjectModel *model = [[moc_ persistentStoreCoordinator] managedObjectModel];
    NSFetchRequest *fetchRequest = [model fetchRequestFromTemplateWithName:@"getQuestionsByParent" substitutionVariables:dictionary];
    NSAssert(fetchRequest, @"Can't find question fetch request");

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"ordinal" ascending:YES];
    NSArray *sortDescriptors = [[NSMutableArray alloc] initWithObjects:sortDescriptor, nil];
    [fetchRequest setSortDescriptors:sortDescriptors];

    NSArray *result = [[NSArray alloc] init];
    result = [moc_ executeFetchRequest:fetchRequest error:&error];
    //return result;

    NSLog(@"fetch request getQuestionsByParent: %u found (sub variables:%@, results:%@)", [result count], dictionary, result);

    NSManagedObject *firstManagedObject = [result objectAtIndex:0];

1 个答案:

答案 0 :(得分:3)

你有你的下载,你有数据。如果已为对象实现自定义子类,则只能查询属性,否则可以使用KVC对对象访问它们。因此,例如,假设您有一个名为“myAttribute”的属性,那么:

NSManagedObject *firstManagedObject = [result objectAtIndex:0];
NSLog(@"firstObject.myAttribute: %@", [firstObject valueForKey:@"myAttribute"]);

如果你有一个对象的自定义子类(问题),它将属性声明为动态属性,那么它将是:

Question *firstQuestion = [result objectAtIndex:0];
NSLog(@"firstQuestion.myAttribute: %@", firstQuestion.myAttribute);