如何在部分NSFetchedResultsController Swift中获取对象数量

时间:2014-09-21 02:44:54

标签: ios swift protocols nsfetchedresultscontroller

如何在Swift中获取NSFetchedResultcController部分中的对象数?

    if let s = self.fetchedResultsController?.sections as? NSFetchedResultsSectionInfo {

    }

正在给我Cannot downcast from '[AnyObject]' to non-@objc protocol type NSFetchedResultsSectionInfo

 var d = self.fetchedResultsController?.sections[section].numberOfObjects

给了我does not have member named 'subscript'

3 个答案:

答案 0 :(得分:12)

您需要将self.fetchedResultsController?.sections投射到ArrayNSFetchedResultsSectionInfo个对象:

if let s = self.fetchedResultsController?.sections as? [NSFetchedResultsSectionInfo]

然后你可以将section传递给下标并获得对象的数量:

if let s = self.fetchedResultsController?.sections as? [NSFetchedResultsSectionInfo] {
    d = s[section].numberOfObjects
}

答案 1 :(得分:4)

我认为Mike S目前接受的答案是Swift 2.0之前的

以下内容对我有用(Swift 2.1):

if let sections = fetchedResultsController?.sections {
    return sections[section].numberOfObjects
} else {
    return 0
}

答案 2 :(得分:0)

这就是我的UITableViewController中的内容(快速4):

override func numberOfSections(in tableView: UITableView) -> Int {
    guard let sections = fetchedResultsController.sections else { return 0 }
    return sections.count
}