• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

[Swift]创建CoreData的两种方式

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/ 
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10696165.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

一、CoreData介绍

CoreData主要分为两部分:
上层是模型层,模型层有NSManagedObjectContext上下文管理着,
底层则是由SQLite实现的持久化部分,通过NSPersistentStore和底层SQL数据库交互,完成存储过程。
这两部分又是由NSPersistentStoreCoordinator持久化协调器关联起来的,上层的存储的数据交由持久化协调器,由协调器指定相关的NSPersistentStore进行相关的数据库存取操作。
使用CoreData要做的第一件事是要创建CoreData栈,从iOS10开始,苹果已经为我们将CoreData栈封装到一个叫NSPersistentContainer的对象里面。

二、创建CoreData

方式一:创建项目时勾选:【User Core Data】,此时AppDelegate.swift会自动创建一些内容。

注意此时的【 AppDelegate.swift 】文件内容

 1 import UIKit
 2 import CoreData
 3 
 4 @UIApplicationMain
 5 class AppDelegate: UIResponder, UIApplicationDelegate {
 6 
 7     var window: UIWindow?
 8 
 9 
10     func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
11         // Override point for customization after application launch.
12         return true
13     }
14 
15     func applicationWillResignActive(_ application: UIApplication) {
16         // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
17         // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
18     }
19 
20     func applicationDidEnterBackground(_ application: UIApplication) {
21         // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
22         // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
23     }
24 
25     func applicationWillEnterForeground(_ application: UIApplication) {
26         // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
27     }
28 
29     func applicationDidBecomeActive(_ application: UIApplication) {
30         // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
31     }
32 
33     func applicationWillTerminate(_ application: UIApplication) {
34         // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
35         // Saves changes in the application's managed object context before the application terminates.
36         self.saveContext()
37     }
38 
39     // MARK: - Core Data stack
40 
41     lazy var persistentContainer: NSPersistentContainer = {
42         /*
43          The persistent container for the application. This implementation
44          creates and returns a container, having loaded the store for the
45          application to it. This property is optional since there are legitimate
46          error conditions that could cause the creation of the store to fail.
47         */
48         let container = NSPersistentContainer(name: "demo")
49         container.loadPersistentStores(completionHandler: { (storeDescription, error) in
50             if let error = error as NSError? {
51                 // Replace this implementation with code to handle the error appropriately.
52                 // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
53                  
54                 /*
55                  Typical reasons for an error here include:
56                  * The parent directory does not exist, cannot be created, or disallows writing.
57                  * The persistent store is not accessible, due to permissions or data protection when the device is locked.
58                  * The device is out of space.
59                  * The store could not be migrated to the current model version.
60                  Check the error message to determine what the actual problem was.
61                  */
62                 fatalError("Unresolved error \(error), \(error.userInfo)")
63             }
64         })
65         return container
66     }()
67 
68     // MARK: - Core Data Saving support
69 
70     func saveContext () {
71         let context = persistentContainer.viewContext
72         if context.hasChanges {
73             do {
74                 try context.save()
75             } catch {
76                 // Replace this implementation with code to handle the error appropriately.
77                 // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
78                 let nserror = error as NSError
79                 fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
80             }
81         }
82     }
83 }

方式二:已创建的项目,添加CoreData文件。

【New File...】->CoreData区域:【Data Model】->输入文件名称,【Create】

Attributes只可以输入小写字母和下划线和数字。不能输入大写字母。

右下角的【Editor Style】可以切换视图样式

注意在【 AppDelegate.swift 】添加以下代码:即新建项目时勾选【User Core Data】时自动生成的那些代码。

引入CoreData

import CoreData

添加CoreData栈属性和方法。注意第10行的内容:

let container = NSPersistentContainer(name: "添加的【Data Model】文件的名称,不带文件类型后缀")

添加内容:

 1  // MARK: - Core Data stack
 2 
 3     lazy var persistentContainer: NSPersistentContainer = {
 4         /*
 5          The persistent container for the application. This implementation
 6          creates and returns a container, having loaded the store for the
 7          application to it. This property is optional since there are legitimate
 8          error conditions that could cause the creation of the store to fail.
 9         */
10         let container = NSPersistentContainer(name: "demo")
11         container.loadPersistentStores(completionHandler: { (storeDescription, error) in
12             if let error = error as NSError? {
13                 // Replace this implementation with code to handle the error appropriately.
14                 // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
15                  
16                 /*
17                  Typical reasons for an error here include:
18                  * The parent directory does not exist, cannot be created, or disallows writing.
19                  * The persistent store is not accessible, due to permissions or data protection when the device is locked.
20                  * The device is out of space.
21                  * The store could not be migrated to the current model version.
22                  Check the error message to determine what the actual problem was.
23                  */
24                 fatalError("Unresolved error \(error), \(error.userInfo)")
25             }
26         })
27         return container
28     }()
29 
30     // MARK: - Core Data Saving support
31     func saveContext () {
32         let context = persistentContainer.viewContext
33         if context.hasChanges {
34             do {
35                 try context.save()
36             } catch {
37                 // Replace this implementation with code to handle the error appropriately.
38                 // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
39                 let nserror = error as NSError
40                 fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
41             }
42         }
43     }
在应用程序将终止applicationWillTerminate()方法中添加保存管理对象上下文的方法。
1  func applicationWillTerminate(_ application: UIApplication) {
2         // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
3         // Saves changes in the application's managed object context before the application terminates.
4         self.saveContext()
5     }

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap