使用 Core Data

Thomas Mak wrote at 2021-04-18.

#ios

Keywords:

  • PersistentContainer
  • PersistentStore
  • PersistentStoreCoordinator
  • Entity
  • EntityDescription
  • Context
  • Managed Object

Managed Object code generation

  • Class Definition: 全部 Xcode 管理
  • Category/Extension: 自己定義 NSManagedObject subclass,Xcode 管理 Extension
  • Manual/None: 自己定義 NSManagedObject subclass 及 Extension
自己管理越多,彈性越大,但亦越要自己動手寫。

新增記錄

let entity = NSEntityDescription.entity(forEntityName: "Friend", in: persistentContainer.viewContext)
        
let friend = Friend(entity: entity!, insertInto: persistentContainer.viewContext)
friend.name = "Jack Chan"
friend.tel = "66661234"
self.saveContext()

搜尋記錄

let fetchRequest:NSFetchRequest<Friend> = Friend.fetchRequest()

do {
    let results = try persistentContainer.viewContext.fetch(fetchRequest)
    print(results.count)
    for friend in results {
        print(friend.name)
        print(friend.tel)
    }
} catch {
    print("Fetch error.")
}

刪除

persistentContainer.viewContext.delete(friend)

保護層級

  • NSFileProtectionComplete
  • NSFileProtectionCompleteUnlessOpen
  • NSFileProtectionCompleteUntilFirstUserAuthentication
  • NSFileProtectionNone
More Detail: https://pspdfkit.com/blog/2017/how-to-use-ios-data-protection/

Apple iOS Security Guide: https://www.apple.com/business/docs/iOS_Security_Guide.pdf


設定 File Protection Tips:

  1. Enable File Protection using the Capabilities tab on your app target
  2. If you do not want the default NSFileProtectionComplete, change this setting in the developer portal under your app id
  3. Make sure Xcode has the new provisioning profile this creates.
  4. For protecting files your app creates, that's it.
  5. To protect Core Data, you need to add the NSPersistentStoreFileProtectionKey: NSFileProtectionComplete option to your persistent store.

storeDescription.setOption(FileProtectionType.completeUnlessOpen as NSObject, forKey: NSPersistentStoreFileProtectionKey)
            container.persistentStoreDescriptions = [storeDescription]

Comments

no comments yet.