Swift教程_CoreData实例(二)_构建数据层

简介:

Swift教程_CoreData实例(一)_构建storyboard

Swift教程_CoreData实例(二)_构建数据层

Swift教程_CoreData实例(三)_构建控制层(列表数据加载、删除数据)

Swift教程_CoreData实例(四)_构建控制层(查询、更新数据)

Swift教程_CoreData实例(五)_构建控制层(添加数据)


三、构建数据层

数据层总体结构包括由CoreData构建的数据模型、通过AppDelegate构建相应的初始化对象。

coredata数据最终的存储类型可以是:SQLite数据库,XML,二进制,内存里,或自定义数据类型。

1.构建数据模型

1.在xcdatamodeld文件添加一个实体entity,并为其添加三个属性,如下图:

2.根据xcdatamodeld中的实体生成对应的实体模型类。选中xcdatamodeld->Editor->Create NSManagedObject SubClass,创建后会发现对应属性带有@NSManaged这个声明。

这里注意,一定要在类上声明@objc(Book),不然会报找不到类的错误:CoreData: warning: Unable to load class named 'Book' for entity 'Book'. Class not found, using default NSManagedObject instead. (创建实体类时自动生成对应@objc声明的教程,请看swift教程_swift开发CoreData_无法找到对应实体类问题

代码如下:

[objc]  view plain  copy
  1. import Foundation  
  2. import CoreData  
  3.   
  4. @objc(Book)  
  5. class Book: NSManagedObject {  
  6.   
  7.     @NSManaged var author: String  
  8.     @NSManaged var title: String  
  9.     @NSManaged var theDate: NSDate  
  10.   
  11. }  

3.在AppDelegate中,需要初始化coredata的对象,我们简单了解下coredata的类功能,该段为网络资源,做了部分更新和修改。
(1)NSManagedObjectContext(数据上下文)
操作实际内容(操作持久层)
作用:插入数据,查询数据,删除数据
(2)NSManagedObjectModel(数据模型)
数据库所有数据结构,包含各实体的定义信息,相当于表
作用:添加实体的属性,建立属性之间的关系
(3)NSPersistentStoreCoordinator(持久化存储连接器)
相当于数据库的连接器
作用:设置数据存储的名字,位置,存储方式,和存储时机
(4)NSManagedObject(数据记录)
相当于数据库中的表记录
(5)NSFetchRequest(数据请求)
相当于查询语句
(6)NSEntityDescription(实体结构)
相当于表结构
(7)后缀为.xcdatamodeld的文件
里面是.xcdatamodel文件,用数据模型编辑器编辑
编译后为.momd或.mom文件
关系如下图:


具体AppDelegate代码如下(注释写的很清楚):

[objc]  view plain  copy
  1. import UIKit  
  2. import CoreData  
  3.   
  4. @UIApplicationMain  
  5. class CoreDataBooksAppDelegate: UIResponder, UIApplicationDelegate {  
  6.       
  7.     var window: UIWindow?  
  8.       
  9.     //app开始启动时调用  
  10.     func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {  
  11.         var navigationViewController = self.window?.rootViewController as UINavigationController  
  12.         var booksTableViewController = navigationViewController.viewControllers[0] as PKOBooksTableViewController  
  13.         booksTableViewController.managedObjectContext = self.managedObjectContext  
  14.         return true  
  15.     }  
  16.       
  17.     //app将要入非活动状态时调用,在此期间,应用程序不接收消息或事件,比如来电话了;保存数据  
  18.     func applicationWillResignActive(application: UIApplication) {  
  19.         self.saveContext()  
  20.     }  
  21.       
  22.     //app被推送到后台时调用,所以要设置后台继续运行,则在这个函数里面设置即可;保存数据  
  23.     func applicationDidEnterBackground(application: UIApplication) {  
  24.         self.saveContext()  
  25.     }  
  26.       
  27.     //app从后台将要重新回到前台非激活状态时调用  
  28.     func applicationWillEnterForeground(application: UIApplication) {  
  29.     }  
  30.       
  31.     //app进入活动状态执行时调用  
  32.     func applicationDidBecomeActive(application: UIApplication) {  
  33.     }  
  34.       
  35.     //app将要退出是被调用,通常是用来保存数据和一些退出前的清理工作;保存数据  
  36.     func applicationWillTerminate(application: UIApplication) {  
  37.         self.saveContext()  
  38.     }  
  39.       
  40.     // MARK: - Core Data stack ,coreData所用  
  41.       
  42.     //应用程序沙箱下的Documents目录路径,自动生成,无需修改  
  43.     lazy var applicationDocumentsDirectory: NSURL = {  
  44.         //NSSearchPathDirectory.DocumentDirectory,可以省略前面的类名  
  45.         let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains.UserDomainMask)  
  46.         return urls[urls.count-1] as NSURL  
  47.         }()  
  48.       
  49.     //NSManagedObjectModel(数据模型),数据库所有模型,包含各实体的定义信息  
  50.     //作用:添加实体的属性,建立属性之间的关系  
  51.     //操作方法:视图编辑器,或代码  
  52.     lazy var managedObjectModel: NSManagedObjectModel = {  
  53.         //xcdatamodeld编译后为momd  
  54.         let modelURL = NSBundle.mainBundle().URLForResource("PKO_Sample_CoreDataBooks", withExtension"momd")!  
  55.         return NSManagedObjectModel(contentsOfURL: modelURL)!  
  56.           
  57.         }()  
  58.       
  59.     //NSPersistentStoreCoordinator(持久化存储连接器),相当于数据库的连接器,大部分都是自动生成,可以自行调整  
  60.     //作用:设置数据存储的名字,位置,存储方式,和存储时机  
  61.     lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {  
  62.         var fileManager = NSFileManager.defaultManager()  
  63.         //sqlite的库路径  
  64.         var storeURL = self.applicationDocumentsDirectory.URLByAppendingPathComponent("PKO_swift_coreDataBooks.sqlite")  
  65.         //应用程序沙箱目录中的sqlite文件是否已经存在,如果它不存在(即应用程序第一次运行),则将包中的sqlite文件复制到沙箱文件目录。即加载初始化库数据  
  66.         //若想重新在模拟器(simulator)中重新使用该sqlite初始化,点击IOS Simulator->Reset Contents and Settings,重置模拟器即可  
  67.         if !fileManager.fileExistsAtPath(storeURL.path!){  
  68.             var defaultStoreURL = NSBundle.mainBundle().URLForResource("PKO_swift_coreDataBooks", withExtension"sqlite")  
  69.             if (defaultStoreURL != nil) {  
  70.                 fileManager.copyItemAtURL(defaultStoreURL!, toURL: storeURL, error: nil)  
  71.             }  
  72.         }  
  73.         //NSMigratePersistentStoresAutomaticallyOption是否自动迁移数据,  
  74.         //NSInferMappingModelAutomaticallyOption是否自动创建映射模型  
  75.         var options = [NSMigratePersistentStoresAutomaticallyOption:true, NSInferMappingModelAutomaticallyOption:true]  
  76.         // 根据managedObjectModel创建coordinator  
  77.         var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)  
  78.         var error: NSError? = nil  
  79.         // 指定持久化存储的数据类型,默认的是NSSQLiteStoreType,即SQLite数据库  
  80.         if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: options, error: &error) == nil {  
  81.             coordinator = nil  
  82.             NSLog("Unresolved error \(error), \(error!.userInfo)")  
  83.             abort()  
  84.         }  
  85.         return coordinator  
  86.         }()  
  87.       
  88.     //NSManagedObjectContext(数据上下文),操作实际内容(操作持久层)  
  89.     //作用:插入数据,查询数据,删除数据  
  90.     lazy var managedObjectContext: NSManagedObjectContext? = {  
  91.         let coordinator = self.persistentStoreCoordinator  
  92.         if coordinator == nil {  
  93.             return nil  
  94.         }  
  95.         var managedObjectContext = NSManagedObjectContext()  
  96.         managedObjectContext.persistentStoreCoordinator = coordinator  
  97.         return managedObjectContext  
  98.         }()  
  99.       
  100.     // MARK: - Core Data Saving support  
  101.       
  102.     //持久化数据,数据落地  
  103.     func saveContext () {  
  104.         if let moc = self.managedObjectContext {  
  105.             var error: NSError? = nil  
  106.             if moc.hasChanges && !moc.save(&error) {  
  107.                 NSLog("Unresolved error \(error), \(error!.userInfo)")  
  108.                 abort()  
  109.             }  
  110.         }  
  111.     }  
  112.       
  113. }  

原文地址:http://blog.csdn.net/ooppookid/article/details/40745191
相关文章
|
4月前
|
IDE 开发工具 Swift
Swift语言的教程
Swift语言的教程
49 1
|
9月前
|
安全 编译器 Swift
一文玩转 Swift 中的 Actors,看看他是如何避免数据竞争的?
一文玩转 Swift 中的 Actors,看看他是如何避免数据竞争的?
84 0
|
Swift 编译器
Swift - 实例对象调用协议方法优先级分析/ witness_methos witness_table分析
本文主要探究: 当一个类遵循了协议,且协议和类都有方法实现时,实例对象调用方法的优先顺序
Swift - 实例对象调用协议方法优先级分析/ witness_methos witness_table分析
|
iOS开发 Swift 编译器
使用 Swift 在 iOS 10 中集成 Siri —— SiriKit 教程
使用 Swift 在 iOS 10 中集成 Siri —— SiriKit 教程 转载地址:http://swift.gg/2016/06/28/adding-siri-to-ios-10-apps-in-swift-tutorial/ 下载 Xcode 8,配置 iOS 10 和 Swift 3 (可选)通过命令行编译 除非你想使用命令行编译,使用 Swift 3.0 的工具链并不需要对项目做任何改变。
1734 0
|
Perl 数据格式 JSON
SWIFT中使用AFNetwroking访问网络数据
AFNetworking 是 iOS 一个使用很方便的第三方网络开发框架,它可以很轻松的从一个URL地址内获取JSON数据。 在使用它时我用到包管理器Cocoapods 不懂的请移步: Cocoapods安装:http://www.
1052 0
|
Swift
SWIFT 之CoreData初试
SWIFT中使用CoreData来保存本地数据,在建立项目的时候把 "Use Core Data"选项选上 项目建立完成后点击后缀为 .xcdatamodeld的那个文件,点击右下角"Add Entity"添加一个Entity后可以修改其名称,接着在"Attributes"下面点击“+”号添加...
776 0
|
Android开发 Swift
swift UI专项训练24 构建函数和侦测网页载入事件
     构建一个方法用来载入网页的请求: func loadurl(url:String ,web:UIWebView){ let aurl = NSURL(string: ur...
759 0
|
Swift
swift UI专项训练8 展示数据
  现在我想要点击表单中的条目,进行标记,再次点击以取消,那么该如何做呢?依然使用的是tableView的重载方法,在 Restaurant中新增一个isCollected的值表示是否收藏,...
863 0