我设置了一个Batch Update,它假设更新了我的UISwitch状态。我把代码放在UITableViewCell类中。在控制台中,它确实返回一条消息,说明结果已更新,但当我返回并再次打开页面时,状态仍然保持不变。但是,当我重建项目时,状态将会更新。
import UIKit
import CoreData
class VerbTenseTableViewCell: UITableViewCell {
@IBOutlet weak var TenseSwitch: UISwitch!
@IBOutlet weak var TenseLabel: UILabel!
var coreDataStack: CoreDataStack! = (UIApplication.shared.delegate as! AppDelegate).coreDataStack
let batchUpdate = NSBatchUpdateRequest(entityName: "Setting")
override func awakeFromNib() {
super.awakeFromNib()
TenseSwitch.addTarget(self, action: #selector(BatchUpdatePresent(switchSate:)), for: .valueChanged)
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func BatchUpdate(Batch: NSBatchUpdateRequest)
{
do {
let batchResult = try coreDataStack.managedContext.execute(Batch) as! NSBatchUpdateResult
print("Records updated \(batchResult.result!)")
} catch let error as NSError {
print("Could not update \(error), \(error.userInfo)")
}
}
func BatchUpdatePresent(switchSate: UISwitch)
{
if(switchSate.isOn && TenseLabel.text == "Présent")
{ print(1)
batchUpdate.propertiesToUpdate = [#keyPath(Setting.present) : true]
batchUpdate.affectedStores = coreDataStack.managedContext.persistentStoreCoordinator?.persistentStores
batchUpdate.resultType = .updatedObjectsCountResultType
}
else if (switchSate.isOn == false && TenseLabel.text == "Présent")
{print(2)
batchUpdate.propertiesToUpdate = [#keyPath(Setting.present) : false]
batchUpdate.affectedStores = coreDataStack.managedContext.persistentStoreCoordinator?.persistentStores
batchUpdate.resultType = .updatedObjectsCountResultType
}
else if (switchSate.isOn == true && TenseLabel.text == "Passé Composé")
{print(3)
batchUpdate.propertiesToUpdate = [#keyPath(Setting.passecompose) : true]
batchUpdate.affectedStores = coreDataStack.managedContext.persistentStoreCoordinator?.persistentStores
batchUpdate.resultType = .updatedObjectsCountResultType
BatchUpdate(Batch: batchUpdate)
}
else if (switchSate.isOn == false && TenseLabel.text == "Passé Composé")
{print(4)
batchUpdate.propertiesToUpdate = [#keyPath(Setting.passecompose) : false]
batchUpdate.affectedStores = coreDataStack.managedContext.persistentStoreCoordinator?.persistentStores
batchUpdate.resultType = .updatedObjectsCountResultType
BatchUpdate(Batch: batchUpdate)
}
}
以下是假设获取更新结果并应用于UISwitch的方法
func get()
{
do {
try coreDataStack.managedContext.fetch(fetchRequest)
Switch = try coreDataStack.managedContext.fetch(fetchRequest)
print(Switch.count)
print(switchState.count)
switchState.append(Switch[0].present)
print("Switch Present is \(switchState[0]) and \(Switch[0].present)")
switchState.append(Switch[0].passecompose)
print("Switch Passe is \(switchState[1]) and \(Switch[0].passecompose)")
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
}
任何人都可以帮我吗?