Core Data to-many关系获取数据

时间:2013-01-20 10:48:48

标签: iphone ios core-data nsfetchedresultscontroller

在我的代码中,我想创建带有List部分的tableView。我使用这样的方案:

enter image description here

我使用NSFetchResultController,我用这种方式定义:

- (NSFetchedResultsController *)fetchedResultsController {

    if (_fetchedResultsController != nil) {
        return _fetchedResultsController;
    }
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription
                               entityForName:@"Item" inManagedObjectContext:coreDataController.masterManagedObjectContext];
    [fetchRequest setEntity:entity];

    NSSortDescriptor *sort = [[NSSortDescriptor alloc]
                          initWithKey:@"addedAt" ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];

    [fetchRequest setFetchBatchSize:20];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"itemIsChecked = 1"];

    [fetchRequest setPredicate:predicate];
    [fetchRequest setResultType:NSDictionaryResultType];

    NSFetchedResultsController *theFetchedResultsController =
    [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                    managedObjectContext:coreDataController.masterManagedObjectContext sectionNameKeyPath:@"toList.listName"
                                               cacheName:nil];
    self.fetchedResultsController = theFetchedResultsController;
    _fetchedResultsController.delegate = self;

    return _fetchedResultsController;
}

现在在cellForRowAtIndexPath中:我想从fetchResultController获取数据,所以我这样做:

Item *item = [self.fetchedResultsController objectAtIndexPath:indexPath];

然后如果我想访问其中一个项目的字段(例如itemText),它会崩溃:

NSLog(@"item itemtext = %@", item.itemText);

有错误:

-[NSKnownKeysDictionary1 itemText]: unrecognized selector sent to instance 0x1215fd90

我的代码出了什么问题?

2 个答案:

答案 0 :(得分:2)

您已设置

[fetchRequest setResultType:NSDictionaryResultType];

因此获取的结果控制器返回NSDictionary个对象,而不是Item个对象。所以你的元素

Item *item = [self.fetchedResultsController objectAtIndexPath:indexPath];

NSDictionary,而不是Item。由于词典没有itemText方法,item.itemText崩溃了。您可以使用

从字典中检索值
NSDictionary *item = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSLog(@"item itemtext = %@", [item objectForKey:@"itemText"]);

但如果您没有特定的理由将结果类型设置为NSDictionaryResultType,则应该删除该行。对获取的结果控制器的更改跟踪(即自动表视图更新)不适用于resultType == NSDictionaryResultType

另请注意,如果已设置sectionNameKeyPath,则必须添加具有相同键路径“toList.listName”的排序描述符,并将其用作获取请求的第一个排序描述符。

答案 1 :(得分:0)

unrecognized selector sent to instance通常由于内存管理不良而发生。检查您是否尝试指向先前发布的对象。同时检查xib中的IBOutlet连接是否为标签itemText