我想使用swift更新实体的多个属性,但找不到任何管理它的教程。我已设法使用以下代码更新实体的单个属性:
//Insert Function
func Insert(dbname : String , attributeName : String , value : String ) {
let check_empty = entityIsEmpty(dbname)
if(check_empty != true){
let saveData = NSEntityDescription.insertNewObjectForEntityForName(dbname, inManagedObjectContext: managedContext)
// add our data
saveData.setValue(value, forKey: attributeName)
//2
do {
try managedContext.save()
//3
check_DB.append(saveData)
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
//check_empty
}else{
//Update procedure
let fetchRequest = NSFetchRequest(entityName: dbname)
do {
let fetchedEntities = try self.managedContext.executeFetchRequest(fetchRequest) as! [SettingInfo]
fetchedEntities.first?.attributeName = value
// ... Update additional properties with new values
} catch {
// Do something in response to error condition
}
do {
try self.managedContext.save()
} catch {
// Do something in response to error condition
}
}
}
但是如何更新实体的多个属性?
例如:实体名称是:dbname
属性名称为:attribute
_ name
我想要更新的属性的值是:value
答案 0 :(得分:1)
您可以使用对NSManagedEntities的键控访问,因此您可以说
if let entity = fetchedEntities.first {
entity[attribute_name]=value
}
答案 1 :(得分:0)
我用以下代码解决了我的问题:
//Update procedure
let fetchRequest = NSFetchRequest(entityName: dbname)
do {
let fetchedEntities = try self.managedContext.executeFetchRequest(fetchRequest) as! [SettingInfo]
let attribute = fetchedEntities[0] as NSManagedObject
attribute.setValue(value , forKey: attributeName)
// ... Update additional properties with new values
} catch {
// Do something in response to error condition
}
do {
try self.managedContext.save()
} catch {
// Do something in response to error condition
}