iOS CoreData 开发

新年新气象,曾经的妹子结婚了,而光棍的我决定书写博客~ 废话结束。

本人不爱使用第三方的东东,喜欢原汁原味的官方版本,本次带来CoreData数据存储篇~

 

创建应用

勾上Use Core Data,不勾也行,后面再添加上去一样的

点击coredata文件,look下

添加实体,点击下面的Add Entity即可,或者通过菜单操作,效果一样。

 

创建一个实体类

 

 

接着,生成代码:

点击Create NSManagedObject Subclass ....,然后选择我们的User,生成代码

 

写代码之前,先来点介绍吧,主要涉及到下面三个东东

1、Managed Object Model , 理解成数据库吧,存储了Entity,就是你要存储的东西

2、Persistent Store Coordinate, 理解成数据库连接吧,里面存放了数据存储到具体的文件等等信息

3、Managed Object Context, 数据上下文,基本上所有的操作都是通过这个的。

 

下面进入写代码状态:

 上面三个对象,一个不可少,所以,先来初始化之类的操作吧

 

1 ///定义三个属性
2 
3 
4 @property(strong,nonatomic) NSManagedObjectModel *cdModel;
5 @property(strong,nonatomic) NSManagedObjectContext *cdContext;
6 @property(strong,nonatomic) NSPersistentStoreCoordinator *cdCoordinator;
 1 - (NSManagedObjectModel *)cdModel
 2 {
 3     if(!_cdModel)
 4     {
 5         _cdModel = [NSManagedObjectModel mergedModelFromBundles:nil];
 6     }
 7     
 8     return _cdModel;
 9 }
10 
11 - (NSPersistentStoreCoordinator *)cdCoordinator
12 {
13     if(!_cdCoordinator)
14     {
15         //find the database
16         NSString *dirPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:DBNAME];
17         NSURL *dbPath = [NSURL fileURLWithPath:dirPath];
18         NSError *err;
19         _cdCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.cdModel];
20         if(![_cdCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:dbPath options:nil error:&err])
21         {
22             NSLog(@"Error %@  %@",err.localizedDescription,err.localizedFailureReason);
23         }
24         dirPath = nil;
25         dbPath = nil;
26     }
27     return _cdCoordinator;
28 }
29 
30 - (NSManagedObjectContext *)cdContext
31 {
32     if(!_cdContext)
33     {
34         _cdContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
35         [_cdContext setPersistentStoreCoordinator:self.cdCoordinator];
36     }
37     return _cdContext;
38 }

下面进行CRUD操作

 1 - (void)insertToDB:(NSString *)username password:(NSString *)password
 2 {
 3     User *u = (User *)[NSEntityDescription insertNewObjectForEntityForName:TBNAME inManagedObjectContext:self.cdContext];
 4     u.username = username;
 5     u.password = password;
 6     NSError *err;
 7     if(![self.cdContext save:&err])
 8     {
 9         NSLog(@"Error %@  %@",err.localizedDescription,err.localizedFailureReason);
10     }
11 }
12 
13 - (void)readFromDb
14 {
15     NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
16     NSEntityDescription *entity = [NSEntityDescription entityForName:TBNAME inManagedObjectContext:self.cdContext];
17     [fetch setEntity:entity];
18     NSError* err;
19     NSArray *results = [self.cdContext executeFetchRequest:fetch error:&err];
20     if(err)
21     {
22         NSLog(@"Error %@  %@",err.localizedDescription,err.localizedFailureReason);
23         return;
24     }
25     [results enumerateObjectsUsingBlock:^(User  *_Nonnull user, NSUInteger idx, BOOL * _Nonnull stop) {
26         NSLog(@"----%@   %@",user.username,user.password);
27     }];
28 }

好的,来测试下:

 

算了,时间来不及了,要睡觉了,就不啰嗦了,下面是完整代码

  1 //
  2 //  ViewController.m
  3 //  CoreDataTest
  4 //
  5 //  Created by winter on 16/2/14.
  6 //  Copyright © 2016年 winter. All rights reserved.
  7 //
  8 
  9 #import "ViewController.h"
 10 #import <CoreData/CoreData.h>
 11 #import "User.h"
 12 
 13 /// define database name
 14 #define DBNAME @"CoreDataTest.sqlite"
 15 /// define entity
 16 #define TBNAME @"User"
 17 
 18 
 19 @interface ViewController ()
 20 {
 21     
 22 }
 23 ///定义三个属性
 24 
 25 
 26 @property(strong,nonatomic) NSManagedObjectModel *cdModel;
 27 @property(strong,nonatomic) NSManagedObjectContext *cdContext;
 28 @property(strong,nonatomic) NSPersistentStoreCoordinator *cdCoordinator;
 29 
 30 
 31 @end
 32 
 33 @implementation ViewController
 34 
 35 #pragma mark - 实现三个属性的getter Method
 36 
 37 - (NSManagedObjectModel *)cdModel
 38 {
 39     if(!_cdModel)
 40     {
 41         _cdModel = [NSManagedObjectModel mergedModelFromBundles:nil];
 42     }
 43     
 44     return _cdModel;
 45 }
 46 
 47 - (NSPersistentStoreCoordinator *)cdCoordinator
 48 {
 49     if(!_cdCoordinator)
 50     {
 51         //find the database
 52         NSString *dirPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:DBNAME];
 53         NSURL *dbPath = [NSURL fileURLWithPath:dirPath];
 54         NSError *err;
 55         _cdCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.cdModel];
 56         if(![_cdCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:dbPath options:nil error:&err])
 57         {
 58             NSLog(@"Error %@  %@",err.localizedDescription,err.localizedFailureReason);
 59         }
 60         dirPath = nil;
 61         dbPath = nil;
 62     }
 63     return _cdCoordinator;
 64 }
 65 
 66 - (NSManagedObjectContext *)cdContext
 67 {
 68     if(!_cdContext)
 69     {
 70         _cdContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
 71         [_cdContext setPersistentStoreCoordinator:self.cdCoordinator];
 72     }
 73     return _cdContext;
 74 }
 75 
 76 
 77 #pragma mark - crud
 78 - (void)insertToDB:(NSString *)username password:(NSString *)password
 79 {
 80     User *u = (User *)[NSEntityDescription insertNewObjectForEntityForName:TBNAME inManagedObjectContext:self.cdContext];
 81     u.username = username;
 82     u.password = password;
 83     NSError *err;
 84     if(![self.cdContext save:&err])
 85     {
 86         NSLog(@"Error %@  %@",err.localizedDescription,err.localizedFailureReason);
 87     }
 88 }
 89 
 90 - (void)readFromDb
 91 {
 92     NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
 93     NSEntityDescription *entity = [NSEntityDescription entityForName:TBNAME inManagedObjectContext:self.cdContext];
 94     [fetch setEntity:entity];
 95     NSError* err;
 96     NSArray *results = [self.cdContext executeFetchRequest:fetch error:&err];
 97     if(err)
 98     {
 99         NSLog(@"Error %@  %@",err.localizedDescription,err.localizedFailureReason);
100         return;
101     }
102     [results enumerateObjectsUsingBlock:^(User  *_Nonnull user, NSUInteger idx, BOOL * _Nonnull stop) {
103         NSLog(@"----%@   %@",user.username,user.password);
104     }];
105 }
106 
107 
108 - (void)viewDidLoad {
109     [super viewDidLoad];
110     // Do any additional setup after loading the view, typically from a nib.
111     [self insertToDB:@"wang" password:@"password"];
112     
113 }
114 
115 - (void)viewDidAppear:(BOOL)animated
116 {
117     [super viewDidAppear:animated];
118     [self readFromDb];
119 }
120 
121 - (void)didReceiveMemoryWarning {
122     [super didReceiveMemoryWarning];
123     // Dispose of any resources that can be recreated.
124 }
125 
126 @end

 

posted @ 2016-02-15 00:08  无姬霸王  阅读(390)  评论(1编辑  收藏  举报