前几天看了一下CoreData的增删改查,于是试着在demo里面加进去使用
增
func saveDishToSQL(cell : mainCollectionViewCell){
let context:NSManagedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
let dish : NSManagedObject = NSEntityDescription.insertNewObjectForEntityForName("Dish",
inManagedObjectContext: context)
//对象赋值
dish.setValue(cell.numOfDish.text!, forKey: "numOfDish")
dish.setValue(cell.titleOfDish.text!, forKey: "titleOfDish")
dish.setValue(cell.authorOfDish.text!, forKey: "dishAuthor")
dish.setValue(cell.day.text!, forKey: "day")
dish.setValue(cell.month.text!, forKey: "month")
dish.setValue(cell.week.text!, forKey: "week")
dish.setValue(cell.descripetionOfDish.text!, forKey: "dishDescribe")
dish.setValue(cell.urlString!, forKey: "urlString")
//保存
do {
try context.save()
print("保存成功!")
} catch {
fatalError("不能保存:\(error)")
}
}
删
func deleteDishFromSQL(cell : mainCollectionViewCell){
let context:NSManagedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
let fetchReq = NSFetchRequest(entityName: "Dish")
do {
let fetchResult = try context.executeFetchRequest(fetchReq)
for re in fetchResult{
let name = re.valueForKey("numOfDish") as! String
if name == cell.numOfDish.text{
context.deleteObject(re as! NSManagedObject)
return
}
}
} catch{
print("查询失败")
}
//保存
do {
try context.save()
print("保存成功!")
} catch {
fatalError("不能保存:\(error)")
}
}
改
func modifiedDishFromSQL(cell : mainCollectionViewCell){
let context:NSManagedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
let fetchReq = NSFetchRequest(entityName: "Dish")
do {
let fetchResult = try context.executeFetchRequest(fetchReq)
for re in fetchResult{
let name = re.valueForKey("numOfDish") as! String
if name == cell.numOfDish.text{
context.setValue("newData", forKey: "numOfDish")
return
}
}
} catch{
print("查询失败")
}
//保存
do {
try context.save()
print("保存成功!")
} catch {
fatalError("不能保存:\(error)")
}
}
查
func getDataFromSQL(){
let context:NSManagedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
let fetchReq = NSFetchRequest(entityName: "Dish")
do {
self.fetchResult = try context.executeFetchRequest(fetchReq)
} catch{
print("查询失败")
}
}