FetchRequest - NSArray element failed to match the Swift Array Element type - Swift 2.0

拜拜、爱过 提交于 2019-12-06 02:41:03

问题


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 !


回答1:


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




回答2:


Solution

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


if (voitures!.count > 0) {

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

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


来源:https://stackoverflow.com/questions/31304638/fetchrequest-nsarray-element-failed-to-match-the-swift-array-element-type-sw

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!