I'm trying to update an attribute in Core Data and then display it. However, when I tell the program to display it, it displays the original value.
Based off the code below, username
is set to a String. I know 100% that username
is saved into Core Data. However, when I try to update it, it saves to Core Data, but prints out the old value. How can I print out only the "newest" value?
import UIKit
import CoreData
class NameSettings: UIViewController {
@IBOutlet var nameText: UITextField!
var userID: String!
var username: String!
override func viewDidLoad() {
super.viewDidLoad()
var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext!
var request = NSFetchRequest(entityName: "Users")
request.returnsObjectsAsFaults = false
var results: NSArray = context.executeFetchRequest(request, error: nil)!
var res = results [0] as NSManagedObject
userID = res.valueForKey("userID") as String
username = res.valueForKey("username") as String
println(username)
nameText.text = username
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func saveTapped(sender: AnyObject) {
//println(userID)
var query = PFQuery(className:"_User")
query.getObjectInBackgroundWithId(userID) {
(update1: PFObject!, error: NSError!) -> Void in
if error == nil {
update1["username"] = self.nameText.text
update1.saveEventually()
var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext!
var updateUser = NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context) as NSManagedObject
updateUser.setValue(self.nameText.text, forKey: "username")
context.save(nil)
//println(self.nameText.text)
self.navigationController?.popToRootViewControllerAnimated(true)
}
}
}
}
NOTE: All the println
's are just for debugging.