Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get number of objects in section, NSFetchedResultsController Swift

How can I get number of objects in section of an NSFetchedResultcController in Swift?

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

    }

is giving me Cannot downcast from '[AnyObject]' to non-@objc protocol type NSFetchedResultsSectionInfo

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

gives me does not have member named 'subscript'

like image 608
SirRupertIII Avatar asked Sep 21 '14 02:09

SirRupertIII


2 Answers

You need to cast self.fetchedResultsController?.sections to an Array of NSFetchedResultsSectionInfo objects:

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

Then you can pass the section to the subscript and get the number of objects:

if let s = self.fetchedResultsController?.sections as? [NSFetchedResultsSectionInfo] {
    d = s[section].numberOfObjects
}
like image 92
Mike S Avatar answered Oct 31 '22 14:10

Mike S


I think the currently accepted answer by Mike S was pre Swift 2.0

The following is working for me (Swift 2.1):

if let sections = fetchedResultsController?.sections {
    return sections[section].numberOfObjects
} else {
    return 0
}
like image 25
So Over It Avatar answered Oct 31 '22 14:10

So Over It