它提供了对象-关系映射(ORM)的功能,可以将OC对象转化成数据,保存在SQLite数据库文件中,也能够将保存在数据库中的数据还原成OC对象在此数据操作期间,我们不需要编写任何SQL语句 这种方式 是苹果提倡咱们使用数据库的一种方式 它能减少咱们在使用sqlite时候的代码量以及复杂度 转化成的数据就是Object的子类,或者说是NSManagedObject的子类 对比关系数据库 和coredata存储的内容
CoreData负责管理这些对象之间的关系
只要Xcode里面建立了visual map就可以新建对象
并把对象添加到数据库里,同时也可以删除、查询
也可以使用属性来访问,数据库中对象内部的数据,底层的通讯由CoreData负责管理
modle里面包含了entry实体相当于数据库中的表 实体里面又包含了:
1、attributes属性 基本数值型属性(如Int16, BOOL, Date等类型的属性)
2、relationship关系 属性之间的关系(可以把另一个对象当做不另一个对象的属性)
3、Fetched Property读取属性 查询属性 相当于数据库中的查询语句
步骤:
1.初始化NSManagedObjectModel对象,加载读取模型文件
2.初始化NSPersistentStoreCoordinator对象,在数据库中读取数据生成 Managed Object,或保存 Managed Object写入数据文件
3.初始化NSManagedObjectContext对象,拿到这个上下文对象操作实体,进行增删改查(CRUD)操作
#pragma mark - Core Data stack
@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
- (NSURL *)applicationDocumentsDirectory {
// The directory the application uses to store the Core Data store file. This code uses a directory named "Bruce.UI_NO_21" in the application's documents directory.
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
//读取模型文件
- (NSManagedObjectModel *)managedObjectModel {
// The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"UI_NO_21" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
//NSPersistentStoreCoordinator负责从数据文件(xml, sqlite,二进制文件等)中读取数据生成 Managed Object,或保存 Managed Object 写入数据文件 负责底层数据文件的读写,一般不需要对它进行操作
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
// Create the coordinator and store
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"UI_NO_21.sqlite"];
NSError *error = nil;
NSString *failureReason = @"There was an error creating or loading the application's saved data.";
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
// Report any error we got.
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
dict[NSLocalizedFailureReasonErrorKey] = failureReason;
dict[NSUnderlyingErrorKey] = error;
error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
// Replace this 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();
}
return _persistentStoreCoordinator;
}
//NSManagedObjectContext参与对数据进行各种操作的整个过程,它持有 Managed Object。我们通过它来监测 Managed Object。监测数据对象有两个作用:支持 undo(撤销信息)/redo(数据库前滚,重做)以及数据绑定。这个类是最常被用到的
- (NSManagedObjectContext *)managedObjectContext {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (!coordinator) {
return nil;
}
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
return _managedObjectContext;
}
#pragma mark - Core Data Saving support
//相当于保存数据的方法 程序意外终止就会调用此方法
- (void)saveContext {
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
NSError *error = nil;
if ([managedObjectContext hasChanges] && ![managedObjectContext 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();
}
}
}
+ (AppDelegate *)appDelegate
{
return (AppDelegate *)[UIApplication sharedApplication].delegate;
}
以下是具体存储数据和查询数据的代码:
- (void)addEntity
{
/**
操作coreData
1、不管增删改查都需要先初始化上下文[app managedObjectContext]
2、插入具体内容到上下文
+ (id)insertNewObjectForEntityForName:(NSString *)entityName inManagedObjectContext:(NSManagedObjectContext *)context;
3、保存 saveContext
*/
// 1.初始化上下文
NSManagedObjectContext *context = [[AppDelegate appDelegate] managedObjectContext];
// 实体描述
Message *message = [NSEntityDescription insertNewObjectForEntityForName:@"Message" inManagedObjectContext:context];
[message setValue:postView.titleTextField.text forKey:@"title"];
[message setValue:postView.contentTextView.text forKey:@"content"];
NSArray *images = @[@"00.jpg",@"11.jpg",@"22.jpg",@"33.jpg",@"44.jpg"];
int arc = arc4random()%images.count;
UserInfo *user = [NSEntityDescription insertNewObjectForEntityForName:@"UserInfo" inManagedObjectContext:context];
[user setValue:images[arc] forKey:@"name"];
[user setValue:@(19+arc) forKey:@"age"];
UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%@.jpg",images[arc]]];
[user setValue:UIImageJPEGRepresentation(image, 1) forKey:@"headerImage"];
[user setValue:message forKey:@"relationship"];
// 保存数据
[[AppDelegate appDelegate] saveContext];
}
//查询数据
/**
谓词NSPredicate条件语句
1、比较运算符>,<,==,>=,<=,!=
可用于数值和字符串等的比较
如:@“age >= 23” 筛选 年纪大于23岁的元素
2、范围运算符:IN、BETWEEN
例:@"number BETWEEN {10,50}"
@"address IN {'河南','北京'}"
3、字符串本身:SELF
例:@“SELF == ‘APPLE’"
4、字符串相关:BEGINSWITH、ENDSWITH、CONTAINS
例:@"name CONTAIN[cd] 'ang'" //包含某个字符串
@"name BEGINSWITH[c] 'sh'" //以某个字符串开头
@"name ENDSWITH[d] 'ang'" //以某个字符串结束
注:[c]不区分大小写[d]不区分发音符号即没有重音符号[cd]既不区分大小写,也不区分发音符号。
(5)通配符:
LIKE模糊查询
例:@"name LIKE[cd] '*b*'" *代表通配符,表示前面后面有一个或多个字符
6、正则表达式
读取coreData
1、读取managedObjectModel
2、找到里面所有实体的名字[model entitiesByName]
3、找到要读取的实体NSEntityDescription *entry = entryDic[@"UserInfo"];
4、初始化查询对象 NSFetchRequest *request = [[NSFetchRequest alloc]init];
5、通过上下文查找 NSArray *list = [context executeFetchRequest:request error:nil];
*/
#pragma mark ----加载数据------
- (void)loadData
{
NSManagedObjectContext *context = [[AppDelegate appDelegate]managedObjectContext];
NSManagedObjectModel *model = [[AppDelegate appDelegate]managedObjectModel];
NSDictionary *entityDic = [model entitiesByName];
NSEntityDescription *entity = entityDic[@"UserInfo"];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
request.entity = entity;
list = [context executeFetchRequest:request error:nil];
NSLog(@"list:%@",list);
if (list.count != 0) {
[showView reloadData];
}
}