过滤CoreData FetchRequest

时间:2012-01-29 18:52:48

标签: ios core-data xcode4 nsfetchrequest

我正在尝试过滤fetchRequest。

我能够获得实体的每个记录的完整细节,但我只想要当前indexPath记录的详细信息。

这是我目前的代码所在:

-(void) fetchStuff {

    NSLog(@"%s", __FUNCTION__); 
    NSError *error = nil;

    NSManagedObjectContext *context = [self managedObjectContext];      
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

    NSEntityDescription *woodgie = [NSEntityDescription entityForName:@"WidgetEntity" inManagedObjectContext:context];

    [fetchRequest setEntity:woodgie];

    NSArray *fetchResults = [managedObjectContext executeFetchRequest:fetchRequest error:&error];


    fetchedObjects = [fetchResults objectAtIndex:selectedRow];


    NSLog(@"selectedRow: %i", selectedRow);  //0

    NSLog(@"fetchedObjects: %@", fetchedObjects);



     for (WidgetEntity *wigglies in fetchedObjects  ) {

         NSSet *peopleSet = [wigglies valueForKey:@"people"];    
         for (id person in peopleSet) {          
             personName = [person valueForKey:@"name"];
             NSLog(@"name = %@", personName);
         }
         NSSet *keywordSet = [wigglies valueForKey:@"keyword"];  
         for (id keyWord in keywordSet) {
              keywordName = [keyWord valueForKey:@"word"];
             NSLog(@"Keyword = %@", keywordName);

.....
}

我在此行获取了一个异常“for(WidgetEntity *在fetchedObjects中摇摆不定){” (countByEnumeratingWithState:objects:count:]:无法识别的选择器发送到实例)..

但事实是 - 我猜测如何过滤数据。

任何帮助/指示都将不胜感激。

2 个答案:

答案 0 :(得分:1)

-(void) fetchStuff {

    NSLog(@"%s", __FUNCTION__); 
    NSError *error = nil;

    NSManagedObjectContext *context = [self managedObjectContext];      
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

    NSEntityDescription *woodgie = [NSEntityDescription entityForName:@"WidgetEntity" inManagedObjectContext:context];

    [fetchRequest setEntity:woodgie];

    NSArray *fetchResults = [managedObjectContext executeFetchRequest:fetchRequest error:&error];


    fetchedRecord = [fetchResults objectAtIndex:selectedRow];


    NSLog(@"selectedRow: %i", selectedRow);  //0

    NSLog(@"fetchedRecord: %@", fetchedRecord); // this looks ok

仔细检查以下两行

     //for (WidgetEntity *wigglies in fetchResults  ) { // crash out here
     WidgetEntity *wigglies = fetchedRecord;

         NSSet *peopleSet = [wigglies valueForKey:@"people"];    
         for (id person in peopleSet) {          
             personName = [person valueForKey:@"name"];
             NSLog(@"name = %@", personName);
         }
         NSSet *keywordSet = [wigglies valueForKey:@"keyword"];  
         for (id keyWord in keywordSet) {
              keywordName = [keyWord valueForKey:@"word"];
             NSLog(@"Keyword = %@", keywordName);

.....
}

答案 1 :(得分:1)

您正在谈论在“已选择的行”中获取记录 - 这表明您已经已经获取记录并正在显示它们,大概是在表格视图。

在这种情况下,无需重新获取实体,只需使用数据源数组中相应索引的对象或获取的结果控制器。