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的数据全部保存或全部取出,更好的方法是:

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