2020-02-17-Demo之iOS使用CoreData

Demo之iOS使用CoreData

准备

Xcode 添加 Coredata.framework 依赖库
确认是否存在 xxxCoreData.xcdatamodeld , 没有就新建一个, 在AppDelegate里可能会新出现一些代码
打开 xxxCoreData.xcdatamodeld 确认以下
ENTITIES里添加xxxEntity(也就是类obj),并添加属性及属性类型
CONFIGURATIONS里确认Entity及Class是否存在上一行的那个xxxEntity,其abstract不勾选(Demo用不上)

代码

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#import <CoreData/CoreData.h>
#import "AppDelegate.h"
#import "xxxCoreData+CoreDataModel.h"
#import "xxxEntity+CoreDataClass.h"
#import "xxxEntity+CoreDataProperties.h"
<UIApplicationDelegate>
@property (retain, strong) NSPersistentContainer *persistentContainer;
/** NSManagedObjectContext */
@property(nonatomic, strong)NSManagedObjectContext *managedObjectContext;
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self initCoreData];
[self insert];
[self tapSearchBtn];
}
// 懒加载
- (NSManagedObjectContext *)managedObjectContext {
// 因为在AppDelegate中已经实现过了,所以在这里是从AppDelegate中去获取
if (!_managedObjectContext) {
// 获取appDelegate对象
AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
_managedObjectContext = appDelegate.persistentContainer.viewContext;
}
return _managedObjectContext;
}
-(void)initCoreData {
NSError *error; //Path to sqlite file.
NSString *path = [NSHomeDirectory() stringByAppendingString:@"/Documents/xxxEntity.sqlite"];
NSURL *url = [NSURL fileURLWithPath:path]; //init the model
NSManagedObjectModel *managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil]; //Establish the persistent store coordinator
NSPersistentStoreCoordinator *persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:managedObjectModel];
if(![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:&error])
{
NSLog(@"Error %@",[error localizedDescription]);
}else{
self.managedObjectContext = [[NSManagedObjectContext alloc ] initWithConcurrencyType:NSMainQueueConcurrencyType];
[self.managedObjectContext setPersistentStoreCoordinator:persistentStoreCoordinator];
}
}
- (xxxEntity *)insert {
NSError *error = nil;
if (self.managedObjectContext == nil) { NSLog(@"managedObjectContext is nil"); return nil; }
xxxEntity * hfile = [NSEntityDescription insertNewObjectForEntityForName:@"xxxEntity" inManagedObjectContext:self.managedObjectContext];
hfile.fileversion = @"version1";
hfile.filename = [NSString stringWithFormat:@"%u", arc4random() % 1000];
hfile.filepath = @"path1";
if ([self.managedObjectContext hasChanges] && ![self.managedObjectContext save:&error]) {
NSLog(@"Unresolved error %@, %@", error, error.userInfo);
return nil;
} else {
NSLog(@"Unresolved error %@", @"插入数据成功");
}
return hfile;
}
- (NSArray *)search {
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"xxxEntity"];
// 执行获取操作,获取所有Student托管对象
NSError *error = nil;
NSArray<xxxEntity *> *hfileArray = [self.managedObjectContext executeFetchRequest:request error:&error];
if (error) {
NSLog(@"%@", [NSString stringWithFormat:@"CoreData Error:%@",error.description]);
} else {
NSLog(@"查找数据成功 %@", NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES));
for (xxxEntity *hfile in hfileArray) {
NSLog(@"%@ %@ %@", hfile.fileversion, hfile.filename, hfile.filepath);
}
}
return hfileArray;
}
// 获取数据的请求对象,指明对实体进行查询操作
- (void)tapSearchBtn {
NSArray *sts = [self search];
if (sts.count == 0) {
return;
}
// 遍历
//[self.dataSources removeAllObjects];
[sts enumerateObjectsUsingBlock:^(xxxEntity * obj, NSUInteger idx, BOOL *stop) {
//[self.dataSources addObject:obj];
NSLog(@"%@", obj);
}];
//[self.tableView reloadData];
}

以下代码是xcode直接生成在AppDelegate里的,不需要重复添加,列在这里只是备个份

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
44
#pragma mark - Core Data stack

@synthesize persistentContainer = _persistentContainer;

- (NSPersistentContainer *)persistentContainer {
// The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
@synchronized (self) {
if (_persistentContainer == nil) {
_persistentContainer = [[NSPersistentContainer alloc] initWithName:@"xxxCoreData"];
[_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
if (error != nil) {
// Replace this implementation with code to handle the error appropriately.
// abort() 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.

/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
NSLog(@"Unresolved error %@, %@", error, error.userInfo);
abort();
}
}];
}
}

return _persistentContainer;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
NSManagedObjectContext *context = self.persistentContainer.viewContext;
NSError *error = nil;
if ([context hasChanges] && ![context save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() 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.
NSLog(@"Unresolved error %@, %@", error, error.userInfo);
abort();
}
}