美文网首页
Swift 3.0 下使用Coredata以及读写本地文件(兼容

Swift 3.0 下使用Coredata以及读写本地文件(兼容

作者: __枫__ | 来源:发表于2017-12-27 11:34 被阅读113次

    一、创建Coredata有两种方式,一种是创建项目的时候创建,另一种是直接command +N选择Coredata创建

    enter description hereenter description here

    二、创建CoreData工具类CodataTool.swift

    //
    //  CodataTool.swift
    //  PricingExcellence
    //
    //  Created by Mr_怪蜀黍 on 2017/7/11.
    //  Copyright © 2017年 LW. All rights reserved.
    //
    
    import UIKit
    import CoreData
    
    class CodataTool: NSObject {
      
      /*
       * 通过AppDelegate单利来获取管理的数据上下文对象,操作实际内容
       * 通过NSEntityDescription.insertNewObjectForEntityForName方法创建实体对象
       * 给实体对象赋值
       * 通过saveContext()保存实体对象
       */
      func SavaDataToCoredataWith(entity:String, dataDic:NSDictionary){
          do{
              //获取数据对象
              var myContext : NSManagedObjectContext!;
              if #available(iOS 10.0, *) {
                  myContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
              } else {
                  myContext = (UIApplication.shared.delegate as! AppDelegate).managedObjectContext
              }
              
              let inserInfo = NSEntityDescription.insertNewObject(forEntityName: entity, into: myContext);
              for (key, value) in dataDic {             // 遍历字典中的所有key value
                  inserInfo.setValue(value, forKey: key as! String);
              }
              
              try myContext.save()
              
              print("保存数据成功")
              
          }catch{
              fatalError();
          }
      }
      
      /*
       查询数据
       */
      func getDataFromCoredataWith(entity:String , key:NSString)->Any{
          //获取数据对象
          var myContext : NSManagedObjectContext!;
          //声明数据的请求
          let request = NSFetchRequest<NSFetchRequestResult>(entityName: entity);
          if #available(iOS 10.0, *) {
              myContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
          } else {
              myContext = (UIApplication.shared.delegate as! AppDelegate).managedObjectContext
          }
          var requestData :Any?
          
          do{
              let dataList = try myContext.fetch(request) as! [NSManagedObject];
              
              for data in dataList as![Product] {
                  
                  if data.product_id == key.intValue{
                      requestData = data
                      return requestData as Any
                  }else{
                      requestData = ""
                  }
              }
          }catch{
              fatalError();
          }
          return requestData as Any
      }
    
      //清除coreData中的数据
      func deleteCoreDataWit(entity:String){
          //获取数据对象
          var myContext : NSManagedObjectContext!;
          //声明数据的请求
          let request = NSFetchRequest<NSFetchRequestResult>(entityName: entity);
          if #available(iOS 10.0, *) {
              myContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
          } else {
              myContext = (UIApplication.shared.delegate as! AppDelegate).managedObjectContext
          }
    
          do{
              let rels = try myContext.fetch(request) as! [NSManagedObject];
              for rel in rels{
                  myContext.delete(rel);
              }
              try myContext.save();
              print("删除数据成功")
              
          }catch{
              fatalError();
          }
          
      }
      
      /**本地文件的读写*/
      func setProductNameData(){
          //取得txt文件路径
          let path = Bundle.main.path(forResource: "ProductName", ofType: "txt")!
          print (path)
          //设定路径
          let url: NSURL = NSURL(fileURLWithPath: path)
          
    //        //定义可变数据变量
    //        let data = NSMutableData()
    //        //向数据对象中添加文本,并制定文字code
    //        data.append("Hello Swift".data(using: String.Encoding.utf8, allowLossyConversion: true)!)
    //        //用data写文件
    //        data.write(toFile: url.path!, atomically: true)
          
          //从url里面读取数据,读取成功则赋予readData对象,读取失败则走else逻辑
          if let readData = NSData(contentsOfFile: url.path!) {
              //如果内容存在 则用readData创建文字列
    //            print((data: readData as Data, encoding: String.Encoding.utf8.rawValue))
              let dataString:NSString = NSString.init(data: readData as Data, encoding: String.Encoding.utf8.rawValue) as Any as! NSString
              print(dataString)
              let array: [Any] = dataString.components(separatedBy: "\n")
             
              for index in 1...55{
                  print(array[index-1])
                  let dic:NSDictionary = ["name":array[index-1],"product_id":index]
                  self.SavaDataToCoredataWith(entity: "Product", dataDic: dic)
              }
              
          } else {  
              //nil的话,输出空
              print("Null")
          }
      
      }
    
    }
    
    

    三、在AppDelegate.swift中关联CoreData

    func applicationWillTerminate(_ application: UIApplication) {
            if #available(iOS 10.0, *) {
                self.saveContext()
            } else {
                // Fallback on earlier versions
            }
        }
        
        // MARK: - Core Data stack
        @available(iOS 10.0 , *)
        lazy var persistentContainer: NSPersistentContainer = {
           
            let container = NSPersistentContainer(name: "ProductCodata")
            container.loadPersistentStores(completionHandler: { (storeDescription, error) in
                if let error = error as NSError? {
                
                    fatalError("Unresolved error \(error), \(error.userInfo)")
                }
            })
            return container
        }()
        
        lazy var applicationDocumentsDirectory: URL = {
            let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
            return urls[urls.count-1]
        }()
        
        lazy var managedObjectModel: NSManagedObjectModel = {
            let modelURL = Bundle.main.url(forResource: "ProductCodata", withExtension: "momd")!
            return NSManagedObjectModel(contentsOf: modelURL)!
        }()
        
        lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
            let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
            let url = self.applicationDocumentsDirectory.appendingPathComponent("ProductCodata.sqlite")
            var failureReason = "There was an error creating or loading the application's saved data."
            do {
                try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
            } catch {
                // Report any error we got.
                var dict = [String: AnyObject]()
                dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
                dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
                
                dict[NSUnderlyingErrorKey] = error as NSError
                let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
                NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
                abort()
            }
            
            return coordinator
        }()
        
        lazy var managedObjectContext: NSManagedObjectContext = {
            let coordinator = self.persistentStoreCoordinator
            var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
            managedObjectContext.persistentStoreCoordinator = coordinator
            return managedObjectContext
        }()
        
        // MARK: - Core Data Saving support
        @available(iOS 10.0 , *)
        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)")
                }
            }
        }
    
    

    四、关于多表的关联

    enter description hereenter description here enter description hereenter description here

    相关文章

      网友评论

          本文标题:Swift 3.0 下使用Coredata以及读写本地文件(兼容

          本文链接:https://www.haomeiwen.com/subject/uqtugxtx.html