当前位置:首页 > 操作系统 > Ios

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{
 3if(!_cdModel)
 4    {
 5         _cdModel = [NSManagedObjectModel mergedModelFromBundles:nil];
 6    }
 7 8return _cdModel;
 9}
1011 - (NSPersistentStoreCoordinator *)cdCoordinator
12{
13if(!_cdCoordinator)
14    {
15//find the database16         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];
20if(![_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    }
27return _cdCoordinator;
28}
2930 - (NSManagedObjectContext *)cdContext
31{
32if(!_cdContext)
33    {
34         _cdContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
35        [_cdContext setPersistentStoreCoordinator:self.cdCoordinator];
36    }
37return _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;
 7if(![self.cdContext save:&err])
 8    {
 9         NSLog(@"Error %@  %@",err.localizedDescription,err.localizedFailureReason);
10    }
11}
1213 - (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];
20if(err)
21    {
22         NSLog(@"Error %@  %@",err.localizedDescription,err.localizedFailureReason);
23return;
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{
 39if(!_cdModel)
 40    {
 41         _cdModel = [NSManagedObjectModel mergedModelFromBundles:nil];
 42    }
 43 44return _cdModel;
 45}
 46 47 - (NSPersistentStoreCoordinator *)cdCoordinator
 48{
 49if(!_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];
 56if(![_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    }
 63return _cdCoordinator;
 64}
 65 66 - (NSManagedObjectContext *)cdContext
 67{
 68if(!_cdContext)
 69    {
 70         _cdContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
 71        [_cdContext setPersistentStoreCoordinator:self.cdCoordinator];
 72    }
 73return _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;
 84if(![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];
 97if(err)
 98    {
 99         NSLog(@"Error %@  %@",err.localizedDescription,err.localizedFailureReason);
100return;
101    }
102     [results enumerateObjectsUsingBlock:^(User  *_Nonnull user, NSUInteger idx, BOOL * _Nonnull stop) {
103         NSLog(@"----%@   %@",user.username,user.password);
104    }];
105}
106107108 - (void)viewDidLoad {
109    [super viewDidLoad];
110// Do any additional setup after loading the view, typically from a nib.111     [self insertToDB:@"wang" password:@"password"];
112113}
114115 - (void)viewDidAppear:(BOOL)animated
116{
117    [super viewDidAppear:animated];
118    [self readFromDb];
119}
120121 - (void)didReceiveMemoryWarning {
122    [super didReceiveMemoryWarning];
123// Dispose of any resources that can be recreated.124}
125126@end

 

原文:http://www.cnblogs.com/wws19125/p/5189724.html


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!