Search code examples
iosuitableviewcore-datansfetchedresultscontrollernsfetchrequest

How to add additional informations in NSFetchedResultsController's section


I have a custom section in UITableView, it has an UIImageView and a UILabel. Using NSFetchedResultsController can i have set image based on section model. Let say section model has imageName and sectionTitle. Based on current implementation i got <NSFetchedResultsSectionInfo> as a section Object. Is this possible to get by custom object in section's object.

Thanks


Solution

  • I think I know what you mean. You created a NSFetchedResultsController object passing a certain entity as an argument for sectionNameKey. So your custom section is based on this entity. This is what you mean by 'section model', I guess.

    If you want to access the objects in the section, you can use the following code:

    //create array for demonstration purposes
    var exampleArray = [[YourEntityType]]()
    
    for sectionInfo in fetchedResultsController.sections! {
    
    //this will give you an array with all the objects in the section            
    let objectsForSection = sectionInfo.objects as! [YourEntityType]
    
    //this will add the array above to another array, so you will have access to all the objects of all the sections      
    exampleArray.append(objectsForSection)   
    }
    

    You can also use keyValue coding, like this:

    //create sectionInfo variable, where 2 is the number of the section (the third section in this example
    let sectionInfo = fetchedResultsController.sections![2]
    
    //access the needed entity object from the sectionInfo
    let exampleVariable = (sectionInfo.objects as! AnyObject).valueForKeyPath("yourEntity") as! YourEntityType
    
    //access the needed attribute object from the sectionInfo
    let anotherExampleVariable = (sectionInfo.objects as! AnyObject).valueForKeyPath("yourEntity.yourAttribute") as! YourAttributeType