我有以下代码:
class RatingsData {
var ratings = [NSManagedObject]()
func fetchFromDatabase() -> Void {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext!
let fetchRequest = NSFetchRequest(entityName: "Rating")
var error: NSError?
let sortDescriptor = NSSortDescriptor(key: "date", ascending: false)
fetchRequest.sortDescriptors = [sortDescriptor]
let fetchedResults = managedContext.executeFetchRequest(fetchRequest, error: &error) as! [NSManagedObject]?
if let results = fetchedResults {
ratings = results
} else {
println("error fetching from database")
}
}
func addTitle(newTitle:String) -> Void {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext!
let entityDescription = NSEntityDescription.entityForName("Rating", inManagedObjectContext: managedContext)
let title = Rating(entity: entityDescription!, insertIntoManagedObjectContext: managedContext)
//new way
title.title = newTitle
println("New rating title \(newTitle) saved")
var error: NSError?
if !managedContext.save(&error) {
println("could not save")
}
}
func addStar(title: String, star: NSData) -> Void {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext!
let entityDescription = NSEntityDescription.entityForName("Rating", inManagedObjectContext: managedContext)
let request = NSFetchRequest()
request.entity = entityDescription
let predicate = NSPredicate(format: "title = %@", title)
request.predicate = predicate
var error: NSError?
var results = managedContext.executeFetchRequest(request, error: &error) as! [NSManagedObject]?
results?[0].setValue(star, forKey: "star")
println("new rating star saved")
if !managedContext.save(&error) {
println("could not save")
}
}
}
评级是实体,标题和星级属性。 它工作正常,但当我点击相同的标题来更改评级时,应用程序崩溃。当点击相同的标题时,我希望能够更新星形图像并在表格视图中显示它。
我无法弄明白该怎么做。