博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
iOS CoreData 开发
阅读量:6160 次
发布时间:2019-06-21

本文共 6827 字,大约阅读时间需要 22 分钟。

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

本人不爱使用第三方的东东,喜欢原汁原味的官方版本,本次带来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 *)cdCoordinator12 {13     if(!_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];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 *)cdContext31 {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)readFromDb14 {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 
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)animated116 {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

 

转载于:https://www.cnblogs.com/wws19125/p/5189724.html

你可能感兴趣的文章
http协议组成(请求状态码)
查看>>
怎样成为一个高手观后感
查看>>
[转]VC预处理指令与宏定义的妙用
查看>>
MySql操作
查看>>
python 解析 XML文件
查看>>
MySQL 文件导入出错
查看>>
java相关
查看>>
由一个异常开始思考springmvc参数解析
查看>>
向上扩展型SSD 将可满足向外扩展需求
查看>>
虚机不能启动的特例思考
查看>>
SQL Server编程系列(1):SMO介绍
查看>>
在VMware网络测试“专用VLAN”功能
查看>>
使用Formik轻松开发更高质量的React表单(三)<Formik />解析
查看>>
也问腾讯:你把用户放在什么位置?
查看>>
CSS Sprites 样式生成工具(bg2css)
查看>>
[转]如何重构代码--重构计划
查看>>
类中如何对list泛型做访问器??
查看>>
C++解析XML--使用CMarkup类解析XML
查看>>
P2P应用层组播
查看>>
Sharepoint学习笔记—修改SharePoint的Timeouts (Execution Timeout)
查看>>