I'm not sure what I'm doing wrong here, but when I save the first time into coredata, it works just fine. When I try to overwrite that, it doesn't.
func testStuff() {
var token = loadLoginData()
println("Token (token)")
saveLoginData("New Token")
var newToken = loadLoginData()
println("Token (newToken)")
}
func saveLoginData(accessToken: String) {
var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context: NSManagedObjectContext = appDel.managedObjectContext!
// save data to core data
var loginData = NSEntityDescription.insertNewObjectForEntityForName("LoginData", inManagedObjectContext: context) as NSManagedObject
loginData.setValue(accessToken, forKey: "accessToken")
context.save(nil)
println("Done saving user")
}
/* Output
Token Optional("12345")
Done saving user
Token Optional("12345")
*/
Load Login Data Func
the function that calls on saveLogin data
func loadLoginData() -> String? {
var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context: NSManagedObjectContext = appDel.managedObjectContext!
var request = NSFetchRequest(entityName: "LoginData")
request.returnsObjectsAsFaults = false
var results: NSArray = context.executeFetchRequest(request, error: nil)!
if (results.count > 0) {
var userData: NSManagedObject = results[0] as NSManagedObject
var accessToken: String = userData.valueForKey("accessToken") as String
return accessToken.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
} else {
println("0 results returned, potential error")
return nil
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…