创建工程步骤:
1.创建新项目时,选择coredata
如果是已有项目,需要添加coredata库引用,并在appdelegate添加代码
2.创建实体
3.添加属性
4.添加类
5.操作数据
// AppDelegate.h
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (readonly,strong,nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly,strong,nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly,strong,nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (void)saveContext;
- (NSURL *)applicationdDocumentsDirectory;
@end
// AppDelegate.m
/*
此处省略部分代码,和以前创建工程时的代码相同
*/
- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
[self saveContext];
}
#pragma mark - Core Data stack
@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
- (NSURL *)applicationdDocumentsDirectory{
NSLog(@"%@",[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]);
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
- (NSManagedObjectModel *)managedObjectModel{
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"TextCoredata" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSURL *storeURL = [[self applicationdDocumentsDirectory] URLByAppendingPathComponent:@"TextCoredata.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];
NSLog(@"Unresolved error %@, %@",error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
- (NSManagedObjectContext *)managedObjectContext {
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]) {
NSLog(@"Unresolved error %@, %@",error, [error userInfo]);
abort();
}
}
}
@end
// ViewController.m
#import "ViewController.h"
#import <CoreData/CoreData.h>
#import "AppDelegate.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)insert
{
//1. 获得NSManagedObjectContext
NSManagedObjectContext *context;
context = [self getManagedObjectContext];
//2. 找到实体结构,并新生成一个实体对象
NSManagedObject *class1 = [NSEntityDescription insertNewObjectForEntityForName:@"Classes" inManagedObjectContext:context];
[class1 setValue:[NSNumber numberWithInt:1] forKey:@"c_id"];
[class1 setValue:@"classOne" forKey:@"c_name"];
NSManagedObject *stu = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:context];
//3. 设置实体属性值
[stu setValue:[NSNumber numberWithInt:1] forKey:@"s_id"];
[stu setValue:@"xiaoqiang" forKey:@"s_name"];
[stu setValue:class1 forKey:@"classes"];
// [stu setValuesForKeysWithDictionary:[NSDictionary dictionaryWithObjectsAndKeys:<#(id), ...#>, nil]]
//4. 调用context,保存实体
NSError *error;
if ([context save:&error]) {
NSLog(@"OK values in");
}
}
- (NSManagedObjectContext *)getManagedObjectContext
{
AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [delegate managedObjectContext];
return context;
}
- (void)search
{
NSManagedObjectContext *context;
context = [self getManagedObjectContext];
NSEntityDescription *stu = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:context];
//构造查询对象
NSFetchRequest *resquest = [[NSFetchRequest alloc]init];
[resquest setEntity:stu];
//执行查询,返回结果集
NSArray *resultArray = [context executeFetchRequest:resquest error:nil];
//遍历结果集
for (NSManagedObject *entity in resultArray) {
NSLog(@"id = %i,name = %@, calss = %@",[[entity valueForKey:@"s_id"] intValue],[entity valueForKey:@"s_name"],[[entity valueForKey:@"classes"] valueForKey:@"c_name"]);
}
}
- (void)upData
{
NSManagedObjectContext *context;
context = [self getManagedObjectContext];
NSEntityDescription *stu = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:context];
NSFetchRequest *request = [NSFetchRequest new];
[request setEntity:stu];
//构造查询条件,相当于where句子
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"s_id = %d",1];
[request setPredicate:predicate];
NSArray *students = [context executeFetchRequest:request error:nil];
if ([students count]>0) {
NSManagedObject *obj = [students lastObject];
[obj setValue:@"小李飞刀" forKey:@"s_name"];
}
[context save:nil];
}
- (void)delete
{
NSManagedObjectContext *context;
context = [self getManagedObjectContext];
NSEntityDescription *stu = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:context];
NSFetchRequest *request = [NSFetchRequest new];
[request setEntity:stu];
//构造查询条件,相当于where句子
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"s_id = %d",1];
[request setPredicate:predicate];
NSArray *students = [context executeFetchRequest:request error:nil];
if ([students count]>0) {
[context deleteObject:[students lastObject]];
}
[context save:nil];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// [self insert];
[self search];
// [self delete];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end