2011-08-31 53 views
5

在下面的代碼:如何使用NSFetchedResultsController和sectionNameKeyPath關聯時獲取節名稱?

NSFetchedResultsController *frc = 
[[NSFetchedResultsController alloc] 
initWithFetchRequest:fetchRequest 
managedObjectContext:myManagedObjectContext 
sectionNameKeyPath:@"store" 
cacheName:@"SomeCache" 
]; 

爲sectionNameKeyPath的@「存儲」值實際上指向到具有name屬性,我真的需要我的節頭標題店鋪實體的關係。

但我的方式代碼設置爲我而不是獲得章節標題像它無法做到: 0x5b504f0 0x5b51190 這些都爲存儲對象是牽強,因爲據我可以告訴代碼數據地址。

我該如何使用NSFetchedResultsController,以便我可以告訴它,我希望它獲取從sectionNameKeyPath提取的任何內容的名稱屬性:@「store」?還是有其他解決方法?

回答

5

嘗試sectionNameKeyPath:@"store.name"

+1

謝謝!只是給道具,以下內容也有幫助:http://stackoverflow.com/questions/2353924/core-data-fetched-results-controller-and-custom-section-header – pulkitsinghal

1

我知道這是一個古老的線程,但我想用斯威夫特加入我的解決方案。

我必須建議此解決方案取決於NSFetchedResultsController返回的節名稱的格式,因此它取決於Apple可以更改的內部實現。

節名包含在持久性數據存儲對象ID的URI,這樣你就可以通過先提取URI,然後讓商店與相應的URI

override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 
    let sectionInfo = fetchedResultsController?.sections![section] 
    let sectionName = sectionInfo?.name 

    //This part depends on the internal implementation of sectionInfo.name 
    let initialRange = sectionName?.rangeOfString("<") 
    let finalRange = sectionName?.rangeOfString(">") 

    let uri = sectionName?.substringWithRange((initialRange?.endIndex)!..<(finalRange?.startIndex)!) 
    let url = NSURL(string: uri!) 

    let store = fetchedResultsController?.managedObjectContext.persistentStoreCoordinator 

    let objectID = store?.managedObjectIDForURIRepresentation(url!) 
    let coreObject = fetchedResultsController?.managedObjectContext.objectWithID(objectID!) 
    //return the correct property from the object as the title 
    let title = ... 
    return title 
} 

對象獲取對象那麼,你需要檢查錯誤(我會在這些let前使用很多guard),但你明白了。

相關問題