Git Hub
коротко

CoreData: Create Read Update Delete

13 апреля 2016, 15:30

https://habrahabr.ru/post/303798/

//
//  DataHelper.swift
//  DaysList
//
//  Created by Kirill on 13/03/2016.
//  Copyright © 2016 Kirill. All rights reserved.
//

import Foundation
import UIKit
import CoreData

class DataHelper{
    
    var context:NSManagedObjectContext
    
    init(context _context:NSManagedObjectContext){
        self.context = _context
    }
    
    class func addRecord(_ _comment:String) -> Int64 {
        
        let newId:Int64 = (getLastId()+1)
        let context = persistentContainer.viewContext
        let day = Day(context: context)
        day.id = newId
        day.comment = _comment
        print("added day id=\(day.id):\(day.comment)")
        
        DataHelper.saveContext()
        
        return day.id
    }
    
    class func getAll(){
        
    }
    
    /// Изменяем элемент
    ///
    /// - Parameters:
    ///   - id: <#id description#>
    ///   - _comment: <#_comment description#>
    class func updateById(id: Int64, comment _comment:String){
      
        let day = getById(id: id)
        
        if (day != nil && (day?.id)! > 0){
            day?.comment = _comment
            saveContext()
        }

    }
    
    
    
    class func deleteById(_ id:Int64){
        let context = persistentContainer.viewContext
        let day = getById(id: id)
        
        if ((day?.id)! > 0){
            context.delete(day!)
        }
    }
    
    class func delete<T>(item:T){
        let context = persistentContainer.viewContext
        context.delete(item as! NSManagedObject)
    }
    
    
    class func getById(id:Int64)-> Day?{
        let context = persistentContainer.viewContext
        let request: NSFetchRequest<Day> = Day.fetchRequest()
        
        request.predicate = NSPredicate(format: "id == %@",
                                        argumentArray: [id])
       
        
        
        var days:[Day] = []
        do{
            days = try context.fetch(request) as [Day]
        }
        catch{
            print("getById error")
        }
        
       let day =  days.first
       return day
    }
    
    
    class func getLastId()-> Int64 {
        let context = persistentContainer.viewContext
        let request: NSFetchRequest<Day> = Day.fetchRequest()
        
        request.predicate = NSPredicate(format: "id == max(id)",
                                        argumentArray: [])
        
        var days:[Day] = []
        do{
            days = try context.fetch(request) as [Day]
        }
        catch{
            print("getLastId error")
        }
        
        let day =  days.first
        return (day?.id)!
    }
    
    static var persistentContainer: NSPersistentContainer = {
        let container = NSPersistentContainer(name: "DaysList")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {

                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()
    
    class func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }
    
}
let resultId =  DataHelper.addRecord("текстовая строка")

Памятка

Обычно файл базы данных лежит где-то здесь

/Users/<USER>/Library/Developer/CoreSimulator/Devices/<DEVICE_ID>/data/Containers/Data/Application/<APPLICATION_ID>/Documents/<FileName>.sqlite
Поделиться
Популярное