我花了几个小时试图让 fetch 在我的胶片表中工作。我需要打开我的 collectionview 项目的电影 View 。我可以按照不同的指南发布,但它总是给我一个空数组。我是新手,很抱歉我的问题,但我需要你的帮助。
这是我的代码:
var taskArrayScheda : NewFilm?
override func viewDidLoad() {
super.viewDidLoad()
self.fetchData()
if(self.taskArrayScheda != nil) {
let schedaOk = taskArrayScheda
mostraDatiNellaScheda(schedaOk!)
} else { print("errore array vuoto") }
}
func mostraDatiNellaScheda(_ sched:NewFilm) {
// get title
titoloScheda.text = sched.titolo
}
func fetchData() {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "NewFilm")
do {
taskArrayScheda = try context.fetch(NewAnime.fetchRequest())
💥ERROR ::::: Cannot assign value of type '[Any]' to type 'NewFilm?'
} catch {
print(error)
}
}
最佳答案
fetch()
返回一个数组。但目前您将 fetch()
结果分配给单个对象 var taskArrayScheda
。
你需要这样的东西:
var taskArrayScheda: [NewFilm]?
那么你应该这样做:
taskArrayScheda = try context.fetch(NewAnime.fetchRequest()) as? [NewFilm]
我在这里假设 NewAnime
是 NewFilm
的子类,从这两个类名来看似乎很有意义。
关于arrays - 为什么在 swift4 中有一个数组为空和错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54910160/