[英]How to update multiple core data attribute in swift 2
我想使用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
您可以使用對NSManagedEntities的鍵控訪問,因此可以說
if let entity = fetchedEntities.first {
entity[attribute_name]=value
}
我已經用以下代碼解決了我的問題:
//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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.