我创建了一个名为Status的实体,并带有一个名为statusUpdate的属性。我希望用户能够首次创建状态,然后将其保存在核心数据中,然后在下一次更新状态时将其保存在核心数据中。这是我所做的:

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)

问题是else if似乎总是运行。我希望它基本上只将Status实体的运行为nil(因此它将仅在有人更新状态时第一次运行),然后在更新状态后,它将仅运行常规if语句。

我不确定我在做什么错???

提前致谢。

最佳答案

代码的第3行会插入一个新的Status对象,因此,每次执行此代码时,都会添加一个额外的对象。新插入的对象的statusUpdate为nil(最有可能)。

当执行提取时,在第6行中,此新的Status对象将与以前保存的所有对象一起包含在results中。因此,当您遍历所有results时,总会有statusUpdate为nil的情况。

我将重组您的代码以首先进行提取,确定是否有任何结果。如果是这样,请更新statusUpdate;如果不是,请创建新对象并设置statusUpdate字段。像这样:

let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let context: NSManagedObjectContext = appDel.managedObjectContext!

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

if let resultsArray = results { // explicitly test for nil results
    if resultsArray.count > 0 {
        // count should be at most one, but just in case we will iterate through:
        for result: AnyObject in resultsArray {
            println("Current User fetched status from Core Data")
            var newStatus = self.updateStatusText.text
            result.setValue(newStatus, forKey: "statusUpdate")
        }
    else { // resultsArray is empty, so insert a new object
        var newStatus = self.updateStatusText.text
        let newUser = NSEntityDescription.insertNewObjectForEntityForName("Status", inManagedObjectContext: context) as NSManagedObject
        newUser.setValue(newStatus, forKey: "statusUpdate")
        println("Status uploaded for the first time")
    }
} else { // fetch returned nil, so log an error:
    println("Nil returned by fetch")
}
context.save(&self.error)

09-09 18:04