CoreData基本使用

CoreData

 

CoreData基本使用

1.1储存数据

step1:导入Coredata框架

import:Coredata

   

step2:储存数据代码

        //Application(应用),managedObjectContext(托管缓冲区)
        //mocAddRestaurant托管缓存区命名
        let mocAddRestaurant = (UIApplication.sharedApplication().delegate as? AppDelegate)?.managedObjectContext
        //"Restaurant"实体名称,Restaurant为实体类
        restaurant = NSEntityDescription.insertNewObjectForEntityForName("Restaurant", inManagedObjectContext: mocAddRestaurant!) as! Restaurant
        
        restaurant.name = nameField.text
        restaurant.type = typeField.text
        restaurant.location = addressField.text
        //这里暂时有image属性代替memo,后面会更改
        restaurant.image = memoField.text
        //存储为NSData类型的图片(png类型)
        if let image = 相片.image{
            restaurant.photo = UIImagePNGRepresentation(image)
        }
        
        do{
            try mocAddRestaurant?.save()
        }catch{
            print(error)
            return
        }

 

1.2取回保存数据

step1:建立取回方法

func 取回保存数据(){
    //获取AppDelegate中的托管缓冲区对象。UIApplication.sharedApplication().delegate as? AppDelegate
    let moc:NSManagedObjectContext = (UIApplication.sharedApplication().delegate as? AppDelegate)?.managedObjectContext
    //使用NSFetchRequest
    let request = NSFetchRequest(entityName: "Fish")
    //让缓冲区执行数据库查询请求executeFetchRequest
    do {
        self.fetchResult = try context.executeFetchRequest(request) as! [Fish]
    } catch{
        print("查询失败")
    }
}

 step2:将以上方法代码放在viewDidAppear方法里执行

 

1.3更高效的方法

相比较把一个entity的数据全部保存或全部取出,更好的方法是:

  • 增加一条新纪录,在列表中插入一行
  • 移除一条记录,列表中移除相应的行

 

转载于:https://www.cnblogs.com/jerry-q1/articles/6260673.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值