CoreData

Posted EchoHG

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CoreData相关的知识,希望对你有一定的参考价值。

第一步:

创建NSManagedObjectModel:

加载:Model.xcdatamodeld 文件

 1 lazy var managedObjectModel: NSManagedObjectModel = {
 2 
 3         if self.isTestMode {
 4 
 5             return NSManagedObjectModel.mergedModel(from: Bundle.allBundles)! //连接项目中所有的 .xcdatamodeld 文件为一个datamodel,这是一个非常好的方法,把多个entity放在各自的xcodemodel文件中分开管理,然后用这个函数连接起来生成一个datamodel
 6 
 7         }
 8 
 9         let modelURL = Bundle.main.url(forResource: "Model", withExtension: "momd")!
10 
11         return NSManagedObjectModel(contentsOf: modelURL)!
12 
13         }()

 第二步:

创建 NSPersistentStoreCoordinator

 1 lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
 2 //     创建本地数据库(数据库协调器)
 3         var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
 4         let url = self.applicationDocumentsDirectory.appendingPathComponent("\(self.modelName).sqlite")
 5         var error: NSError? = nil
 6         var failureReason = "There was an error creating or loading the application‘s saved data."
 7         let optionsDictionary = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true]
 8         let storeType = self.isTestMode ? NSInMemoryStoreType : NSSQLiteStoreType
 9         do {
10             try coordinator!.addPersistentStore(ofType: storeType, configurationName: nil, at: url, options: nil)
11         } catch {
12             do {
13                 try coordinator!.addPersistentStore(ofType: storeType, configurationName: nil, at: url, options: optionsDictionary)
14             } catch {
15                 do {
16                     try FileManager.default.removeItem(at: url)
17                 } catch {
18                     do {
19                         try coordinator!.addPersistentStore(ofType: storeType, configurationName: nil, at: url, options: nil)
20                     } catch {
22                         var dict = [String: AnyObject]()
23                         dict[NSLocalizedDescriptionKey] = "Failed to initialize the application‘s saved data" as AnyObject?
24                         dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
25                         
26                         dict[NSUnderlyingErrorKey] = error as NSError
27                         let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
30                         NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
31                         abort()
32                     }
33                 }
34             }
35         }
36         
37         return coordinator
38         }()    

 

 第三步:

数据库关联到缓存区域(托管对象管理)

1 NSManagedObjectContext *context = [CoreDataManager sharedManager].backgroundContext;
2             NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"CDProduct"];
3             request.predicate = [NSPredicate predicateWithFormat:@"orderProduct = nil"];
4             NSArray *results = [context executeFetchRequest:request error:nil];
5             [context performBlockAndWait:^{
6                 for (CDProduct * p in results) {
7                     [context deleteObject:p];
8                 }
9         }    

 

以上是关于CoreData的主要内容,如果未能解决你的问题,请参考以下文章

CoreData - 获取代码 swift3

iOS:SharedCoreData 示例代码 (iCloud + CoreData) |如何合并更改

一行代码解决CoreData托管对象属性变更在SwiftUI中无动画效果的问题

如何从 CoreData-Entities 获取一些值到代码中

iCloud 与 Coredata 同步

创建 CoreData 关系导致代码中出现 20 多个错误