CoreData 保存,获取和删除

eg:ENTITYS : ListEntity,attribute : itemToSave(String类型)

1> 保存 (四步)

//初始化一个listItems
var listItems  = [NSManagedObject]()

func saveItem(itemToSave: String) {
    
    //1、获取总代理(appDelegate)和托管对象总管(managedObjectContext )
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContex = appDelegate.managedObjectContext
    
    2、建立一个entity
    let entity = NSEntityDescription.entityForName("ListEntity", inManagedObjectContext: managedContex)
    let item = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContex)
    
    //3、保存数据到NSManagedObject实例(item)
    item.setValue(itemToSave, forKey: "item")

    //4、保存entity到托管对象内容总管中(managedObjectContext )
    do {
        try managedContex.save()
        listItems.append(item)
        
    } catch {
        
        print("error")
    }

}

2> 获取 (三步)

    //1、获取总代理(appDelegate)和托管对象总管
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContex = appDelegate.managedObjectContext
    
    //2、建立一个获取数据请求
    let fetchRequest = NSFetchRequest(entityName: "ListEntity")
    
    //3、执行请求,获取数据
    do {
        let results = try managedContex.executeFetchRequest(fetchRequest)
        listItems = results as! [NSManagedObject]
        self.tableView.reloadData()
        
    } catch {
        
        print("error")
    }
    
}

3>删除

      //1、获取总代理(appDelegate)和托管对象总管         
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        let managedContex = appDelegate.managedObjectContext
        
        tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Right)
        
        //2、删除1                                                             
        managedContex.deleteObject(self.listItems[indexPath.row])
        do {
            try managedContex.save()
            //2、删除2  
self.listItems.removeAtIndex(indexPath.row)
            self.tableView.reloadData()
        } catch {
            print("error: delete ")
        }

你可能感兴趣的:(CoreData 保存,获取和删除)