5

I want to do a NSFetchRequest to display my data into a UICollectionView :

import UIKit
import CoreData

let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context: NSManagedObjectContext = appDelegate.managedObjectContext
class GarageViewController: UIViewController, UICollectionViewDelegate,UICollectionViewDataSource {

@IBOutlet weak var backgroundView: UIImageView!

@IBOutlet weak var collectionView: UICollectionView!

var voitures: [Voiture]  = [Voiture]()

override func viewDidLoad() {
    super.viewDidLoad()

    collectionView.reloadData()

    let fetchRequest = NSFetchRequest(entityName: "Voiture")
    fetchRequest.resultType = .DictionaryResultType

    do {
        try voitures = context.executeFetchRequest(fetchRequest) as! [Voiture]
    }
    catch let fetchError as NSError {
        print("VoitureFetch error: \(fetchError.localizedDescription)")
    }

    if (voitures.count > 0) {
        for voiture in voitures as [Voiture] {

            print(voiture.nom!)

        }
    }
    else {
        print("Aucune voiture")
    }

}

When I run the code I get that error :

fatal error: NSArray element failed to match the Swift Array Element type

Thank's for your help !

2
  • 2
    What is in the array returned by the fetch request. It isn't Voiture objects. It is probably NSManagedObject instances. Commented Jul 8, 2015 at 22:10
  • 1
    You can answer your own question (instead of posting Solution in your question), makes things easier for people stumbling on this in the future. Commented Jul 17, 2015 at 9:15

2 Answers 2

15

I had the same problem. The issue was due to not setting the class property for the entity in model file.

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

Cool thanks for pointing this out. Also needed this post stackoverflow.com/questions/26613971/… to get it working for me. I had to include @objc(ClassName)
In Addition to this, after setting the class name, set the module name to "Current Product Module".
3

Solution

var voitures: [NSManagedObject]?  = [NSManagedObject]()


if (voitures!.count > 0) {

        let voiture: NSManagedObject = voitures![indexPath.row]

        print((voiture.valueForKey("nom") as? String))
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.