mardi 27 janvier 2015

How do I check if core data class is nil. in SWIFT

I have created an Entity called Status with an attribute called statusUpdate. I want the user to be able to create a status for the first time which would then be saved in core data, then when the status is next updated to save over the old status in core data. Here is what i've done:



let appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext!
let newUser = NSEntityDescription.insertNewObjectForEntityForName("Status", inManagedObjectContext: context) as NSManagedObject

var request = NSFetchRequest(entityName: "Status")
request.returnsObjectsAsFaults = false
var results = context.executeFetchRequest(request, error: &self.error)

if (results?.count > 0) {

for result: AnyObject in results! {

if var oldStatus = result.valueForKey("statusUpdate") as? String{

println("Current User fetched status from Core Data")
var newStatus = self.updateStatusText.text
result.setValue(newStatus, forKey: "statusUpdate")


}else if ((result.valueForKey("statusUpdate")) == nil) {

var newStatus = self.updateStatusText.text
newUser.setValue(newStatus, forKey: "statusUpdate")
println("Status uploaded for the first time")
}
}

}
context.save(&self.error)


The problem is the else if seems to always run. I want it to basically only run of the Status entity is nil (so it will only run for the first time somebody updates a status) and then when the status is updated after that it will run just the regular if statement.


I'm not sure what i'm doing wrong???


Thanks in advance.


Aucun commentaire:

Enregistrer un commentaire