我创建了一个名为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(所以它只会在第一次有人更新状态时运行)然后当状态更新之后它将只运行常规{{1声明。
我不确定我做错了什么???
提前致谢。
答案 0 :(得分:1)
代码的第3行插入一个新的Status
对象,因此每次执行此代码时,都会添加一个额外的对象。新插入的对象的statusUpdate
为零(最有可能)。
执行提取时,在第6行中,这个新的Status
对象将与您之前保存的所有对象一起包含在results
中。因此,当您遍历所有results
时,总会有一个statusUpdate
为零的文件。
我会重构您的代码以先进行获取,确定是否有任何结果。如果是,请更新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)
答案 1 :(得分:0)
if (var oldStatus = result.valueForKey("statusUpdate") as? String) != nil{
println("Current User fetched status from Core Data")
var newStatus = self.updateStatusText.text
result.setValue(newStatus, forKey: "statusUpdate")
}else {
var newStatus = self.updateStatusText.text
newUser.setValue(newStatus, forKey: "statusUpdate")
println("Status uploaded for the first time")
}