数据持久化

1 .plist文件数据的读取和存储

每次在Xcode中新建一个iOS项目后,都会自己产生一个.plist文件,里面记录项目的一些配置信息。我们也可以自己创建.plist文件来进行数据的存储和读取。 .plist文件其实就是一个XML格式的文件,其支持的数据类型有(NS省略)Dictionary、Array、Boolean、Data、Date、Number、String这些类型。

创建一个plist文件

打开plist文件,通过点击"+"或右击选择[Add Row],往plist文件中添加一行新的键值对

将信息写入plist文件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
 //获取新建的PList文件的地址
  let filePath:String? = Bundle.main.path(forResource: "test", ofType: "plist"

  //新建一个字典
  let dic: NSMutableDictionary = NSMutableDictionary()
                dic.setObject("AAA", forKey: "first" as NSCopying)
                dic.setObject("BBB", forKey: "second" as NSCopying)
                dic.setObject(["CCC","DDDD"], forKey: "third" as NSCopying)

  //将新建的字典写入Plist文件
  dic.write(toFile: filePath!, atomically: true)

  //读取文件中的信息
  let data : NSMutableDictionary = NSMutableDictionary.init(contentsOfFile: filePath!)!      
  let message = data.description
  print(message)
  print(data["third"]!)

2 .coreData的数据的存取

创建带coreData的项目,在创建项目的时候,勾选上Use Core Data选项

创建数据表,点击Add Entity

追加属性,点击Attributes 的 ➕ 号

增删改查操作

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
         //获取管理的数据上下文 对象
  static  func getContext () -> NSManagedObjectContext {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        return appDelegate.persistentContainer.viewContext
    }

    //查询数据表Customer
    func getCustomers(){
        //声明数据的请求
        let fetchRequest = NSFetchRequest<Customer>(entityName: "Customer")

        //此处为添加查询条件
        // fetchRequest.predicate =  NSPredicate(format: "name = %@ && age = %@", "aaa","12")
        do {
            let results = try CustomerArray.getContext().fetch(fetchRequest)
            customers = results
            print(customers.count)
        } catch  {
            print(error)
        }
    }

    //新建对象
    let newCustomer = Customer(context: CustomerArray.getContext())
        newCustomer.name = "zc"
        newCustomer.age = "23"
        newCustomer.phone = "13401335852"
        newCustomer.address = ""
    //直接保存对象,对于修改的对象也直接保存即可
    let context = CustomerArray.getContext()
        do{
            try context.save()
        }catch{
            print(error)
        }

     //删除对象
        context.delete(customer)
        do {
            try context.save()
        }catch{
            print(error)
        }
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
     // 直接对表中的数据进行查询修改
            let request =   NSBatchUpdateRequest(entityName: "Customer")
         request.predicate =  NSPredicate(format: "name = %@ && age = %@" ,"zhangsan" ,"25")
         request.propertiesToUpdate = ["age":"30"]

        do{
            try context.execute(request)
//            try context.save()
        }catch{
            print(error)
        }
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
        //查询删除
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName:"Customer")
                //设置查询条件
        let predicate = NSPredicate(format: "name = %@ && age = %@" ,"zhangsan" ,"25")
        fetchRequest.predicate = predicate
        let fetch = NSBatchDeleteRequest(fetchRequest: fetchRequest)
        do {
            try context.execute(fetch)
        }catch{
            print(error)
        }