参考我之前的问题:Unique value of object to use in section Swift
我现在的问题是核心数据。这是在前面的代码之后保存数据的代码,用于填充section和table:
let app = UIApplication.sharedApplication().delegate as! AppDelegate
let context = app.managedObjectContext
let entity = NSEntityDescription.entityForName("Movie", inManagedObjectContext: context)!
let movie = Movie(entity: entity, insertIntoManagedObjectContext: context)
movie.title = title.text
movie.plot = plot.text
movie.genre = genre.text
context.insertObject(movie)
do {
try context.save()
} catch {
print("Could not save movie")
}
并获取数据:
let app = UIApplication.sharedApplication().delegate as! AppDelegate
let context = app.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Movie")
do {
let results = try context.executeFetchRequest(fetchRequest)
self.loadMovie = results as! [Movie]
} catch let err as NSError {
print(err.debugDescription)
}
} 但是我没有收到loadMovie Line上的错误..
我哪里错了?
答案 0 :(得分:0)
正如您上一个问题的回答所示,self.loadMovie
现在有[String:[Movie]]
类型,因此您应该尝试将results
转换为[String:[Movie]]
。
请尝试self.loadMovie = results as! [String:[Movie]]
。
答案 1 :(得分:0)
首先,删除行
context.insertObject(movie)
因为该对象已插入let movie =
行。
要加载电影,您需要使用insertMovie(movie : Movie)
功能重新创建数据结构。
let movies = try context.executeFetchRequest(fetchRequest) as! [Movie]
loadMovie.removeAll()
for movie in movies {
insertMovie(movie)
}