ios - updating with Core Data -
i have following code:
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 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") } } }
rating entity, title , star attribute. works fine, when tap onto same title change rating, app crashes. when tapping on same title, able update star image , display in table view.
i can't figure out how it.
Comments
Post a Comment