2013-01-20 120 views
0

在我的代碼中,我想創建帶有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

您已設置

[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」的排序描述符,並將其用作獲取請求的第一個排序描述符。

+0

完美診斷.. +1。 –

+0

很好的答案,謝謝馬丁! – edzio27

0

unrecognized selector sent to instance一般由於內存管理不當而發生。檢查你是否試圖指出一個早些時候發佈的對象。同時檢查xib中的IBOutlet連接是否爲itemText