Swift中CoreData的基本用法

前几天看了一下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("查询失败")
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容