1.Core Data 含義:
Core Data(數(shù)據(jù)庫)是數(shù)據(jù)持久化存儲的最適合的方式,通過一系列特性避免使用SQL的一些麻煩咧织,還能合理管理內(nèi)存。
Core Data是iOS5之后才出現(xiàn)的一個框架籍救。
它提供了對象-關(guān)系映射(ORM)的功能习绢,即能夠?qū)C對象轉(zhuǎn)化成數(shù)據(jù),保存在SQLite數(shù)據(jù)庫文件中蝙昙,也能夠?qū)⒈4嬖跀?shù)據(jù)庫中的數(shù)據(jù)還原成OC對象毯炮。
在此數(shù)據(jù)操作期間,我們不需要編寫任何SQL語句耸黑,這個有點類似于著名的Hibernate持久化框架桃煎,不過功能肯定是沒有Hibernate強大的。
2.Core Data 優(yōu)點:
利用Core Data框架大刊,我們就可以輕松地將數(shù)據(jù)庫里面的2條記錄轉(zhuǎn)換成2個OC對象为迈,也可以輕松地將2個OC對象保存到數(shù)據(jù)庫中,變成2條表記錄缺菌,而且不用寫一條SQL語句葫辐。
在Core Data,需要進行映射的對象稱為實體(entity)伴郁,而且需要使用Core Data的模型文件來描述app中的所有實體和實體屬性耿战。
3.Core Data 支持的存儲類型:
SQLite、內(nèi)存焊傅、二進制剂陡、XML、自定義數(shù)據(jù)類型
4.Core Data 的使用:
例子:對用戶輸入的信息放入數(shù)據(jù)庫狐胎,可對數(shù)據(jù)進行保存鸭栖、刪除、查看
||
||
方法saveContext表示:保存數(shù)據(jù)到數(shù)據(jù)庫。
方法applicationDocumentsDirectory表示:應(yīng)用程序沙盒下的Documents目錄路徑溅话。
||
||
簡單了解NSManagedObject:
1.通過Core Data從數(shù)據(jù)庫取出的對象飞几,默認情況下都是NSManagedObject對象带射。
2.NSManagedObject的工作模式有點類似于NSDictionary對象,通過鍵-值對來存取所有的實體屬性:
1> setValue:forKey:存儲屬性值(屬性名為key)
2> valueForKey:獲取屬性值(屬性名為key)
||
||
||
||
Contactinformation.h文件Demo:
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h> //導(dǎo)入分類
NS_ASSUME_NONNULL_BEGIN
@interface Contactinformation : NSManagedObject
//返回實體名(類名)
+ (NSString *)entityName;
@end
NS_ASSUME_NONNULL_END
#import "Contactinformation+CoreDataProperties.h"
||
Contactinformation.m文件Demo:
#import "Contactinformation.h"
@implementation Contactinformation
+ (NSString *)entityName{
return @"Contactinformation";
}
//重寫description
- (NSString *)description{
return [NSString stringWithFormat:@"<name = %@, age = %@, sex = %@, telephone = %@, birthday = %@, adress = %@>",self.name,self.age,self.sex,self.telephone,self.birthday,self.adress];
}
@end
||
####### 封裝保存窟社、插入、刪除數(shù)據(jù)庫的數(shù)據(jù)方法
CoreDataManager.h文件的Demo
//封裝保存绪钥、插入灿里、刪除數(shù)據(jù)庫數(shù)據(jù)
#import <Foundation/Foundation.h>
@interface CoreDataManager : NSObject
//插入
+ (BOOL)insertObjectWithParameter:(NSDictionary *)parameters entityName:(NSString *)entityName;
//查詢
+ (NSArray *)readentityName:(NSString *)entityName predicate:(NSString *)predicateString;
//刪除
+ (BOOL)removeWithEntityName:(NSString *)entityName predicate:(NSString *)predicateString;
@end
CoreDataManager.m文件的Demo
#import "CoreDataManager.h"
#import "AppDelegate.h"
@implementation CoreDataManager
//委托對象上下文方法
+ (NSManagedObjectContext *)managedObjectContext{
//獲取程序唯一的委托對象上下文,用于存儲程腹、查詢匣吊、刪除
return [(AppDelegate *)[UIApplication sharedApplication].delegate managedObjectContext];
}
//插入
+ (BOOL)insertObjectWithParameter:(NSDictionary *)parameters entityName:(NSString *)entityName{
if (entityName.length == 0) { //異常情況判斷
return nil;
}
//獲取數(shù)據(jù)(已存在parameters對象中)
//用實體名實例化模型對象
NSManagedObject *contect = [NSEntityDescription insertNewObjectForEntityForName:entityName inManagedObjectContext:[self managedObjectContext]]; //用NSManagedObject父類接收
//把數(shù)據(jù)存入實體對象
for (NSString *key in parameters) {
//KVC (建立的值一樣才能用KVC)
[contect setValue:parameters[key] forKey:key];
}
//保存同步文件
BOOL success = [[self managedObjectContext] save:nil];
NSLog(@"是否保存成功:%d",success);
return success;
}
//查詢
+ (NSArray *)readentityName:(NSString *)entityName predicate:(NSString *)predicateString{
if (entityName.length == 0) { //異常情況判斷
return nil;
}
//1.實例化查詢請求類
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:entityName];
//2.配置查詢條件(可選操作)
if (predicateString.length > 0) {
fetchRequest.predicate = [NSPredicate predicateWithFormat:predicateString]; //年齡等于6才能保存
}
//3.執(zhí)行查詢
NSArray *results = [[self managedObjectContext] executeFetchRequest:fetchRequest error:nil];
NSLog(@"results = %@",results);
return results;
}
//刪除
+ (BOOL)removeWithEntityName:(NSString *)entityName predicate:(NSString *)predicateString{
if (entityName.length == 0) { //異常情況判斷
return nil;
}
NSArray *results = [self readentityName:entityName predicate:predicateString]; //調(diào)用查詢數(shù)據(jù)庫方法 //1.2.3.步驟在查詢數(shù)據(jù)庫方法中
//4.數(shù)據(jù)對象的刪除 (從數(shù)據(jù)庫中刪除)
for (id object in results) { //所有數(shù)據(jù)
[[self managedObjectContext] deleteObject:object];
}
//5.保存同步數(shù)據(jù)
BOOL success = [[self managedObjectContext] save:nil];
NSLog(@"是否刪除成功:%d",success);
return success;
}
@end
||
下面ViewController.m文件是關(guān)于iOS界面與如何使用數(shù)據(jù)庫的Demo
#import "ViewController.h"
#import "Contactinformation.h"
#import "AppDelegate.h"
#import "CoreDataManager.h"
static const NSInteger TEXTFIELD_BASE_TAG = 20;
@interface ViewController ()
@property (nonatomic, strong) NSArray *keys;
@end
@implementation ViewController{
//聲明變量
//委托對象上下文
NSManagedObjectContext *_context;
}
//初始化
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
self = [super initWithCoder:aDecoder];
if (self) {
//獲取程序唯一的委托對象上下文,用于存儲寸潦、查詢色鸳、刪除
_context = [(AppDelegate *)[UIApplication sharedApplication].delegate managedObjectContext]; //有一個強轉(zhuǎn)否則不認識 //獲取程序單例(唯一)
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
_keys = @[@"adress",@"name",@"age",@"sex",@"telephone",@"birthday"];
for (int i = 0; i < 6; i ++) {
UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(30, (20 + 30 * i) * 2, 100, 30)];
label1.text = [_keys[i] stringByAppendingString:@":"];
label1.textAlignment = NSTextAlignmentRight;
[self.view addSubview:label1];
UITextField *text = [[UITextField alloc] initWithFrame:CGRectMake(140, (20 + 30 * i) * 2, 200, 30)];
text.backgroundColor = [UIColor whiteColor];
text.layer.borderColor = [UIColor grayColor].CGColor;
text.layer.borderWidth = 1;
text.tag = TEXTFIELD_BASE_TAG + i;
text.layer.cornerRadius = 8;
[self.view addSubview:text];
}
NSArray *array1 = @[@"save",@"read",@"clear"];
for (int i = 0; i < 3; i ++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
button.frame = CGRectMake((30 * i + 20) * 3, 400, 50, 30);
button.backgroundColor = [UIColor clearColor];
[button setTitle:array1[i] forState:UIControlStateNormal];
button.titleLabel.font = [UIFont systemFontOfSize:18];
button.tag = 100 + i;
[button addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
}
- (void)button:(UIButton *)sender{
if (sender.tag == 100) {
[self insertContext];
}else if (sender.tag == 101){
[self readContext];
}else{
[self clearContext];
}
}
//插入
- (void)insertContext{
//采用封裝
[CoreDataManager insertObjectWithParameter:[self contactInformation] entityName:[Contactinformation entityName]];
}
//查詢
- (void)readContext{
//采用封裝
[CoreDataManager readentityName:[Contactinformation entityName] predicate:nil];
}
//刪除
- (void)clearContext{
//采用封裝
[CoreDataManager removeWithEntityName:[Contactinformation entityName] predicate:nil];
}
//文本框內(nèi)容獲取方法
- (NSDictionary *)contactInformation{
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
for (NSInteger i = 0; i < _keys.count; i ++) {
UITextField *field = (UITextField *)[self.view viewWithTag:TEXTFIELD_BASE_TAG + i];
if (field.text.length > 0) {
[dic setObject:field.text forKey:_keys[i]];
}
}
return dic;
}
@end
例子演示結(jié)果:
Core Data中的核心對象