http://blog.csdn.net/q199109106q/article/details/8563438
// // MJViewController.m // 数据存储5-Core Data // // Created by mj on 13-4-16. // Copyright (c) 2013年 itcast. All rights reserved. // #import "MJViewController.h" #import <CoreData/CoreData.h> #import "NSString+File.h" #import "Person.h" @interface MJViewController () @property (nonatomic, retain) NSManagedObjectContext *context; @end @implementation MJViewController - (void)viewDidLoad { [super viewDidLoad]; // 初始化上下文对象 [self initContext]; // 插入数据 //[self addData]; //[self addPerson]; // 删除数据 //[self deleteData]; // 查询数据 [self findPerson]; // 更改数据 //[self updateData]; } - (void)dealloc { [_context release]; [super dealloc]; } #pragma mark 查询数据 - (void)findPerson { // 初始化查询对象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"]; NSArray *array = [self.context executeFetchRequest:request error:nil]; for (Person *person in array) { NSLog(@"name=%@,age=%@", person.name, person.age); } } #pragma mark 插入数据 - (void)addPerson { // 初始化一个跟上下文关联的对象 Person *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.context]; person.name = @"mj"; person.age = [NSNumber numberWithInt:10]; [self.context save:nil]; } #pragma mark 删除数据 - (void)deleteData { // 初始化查询对象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"]; // 设置条件过滤 where age < 50 request.predicate = [NSPredicate predicateWithFormat:@"age < %i", 50]; NSArray *array = [self.context executeFetchRequest:request error:nil]; for (NSManagedObject *person in array) { // 删除掉的person对象就不会跟context关联了 [self.context deleteObject:person]; } // 将所有跟上下文相关联的对象同步到数据库 [self.context save:nil]; } #pragma mark 查询数据 - (void)updateData { // 初始化查询对象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"]; // 设置条件过滤 where age > 20 request.predicate = [NSPredicate predicateWithFormat:@"age > %i", 20]; NSArray *array = [self.context executeFetchRequest:request error:nil]; for (NSManagedObject *person in array) { [person setValue:[NSNumber numberWithInt:50] forKey:@"age"]; } // 将所有跟上下文相关联的对象同步到数据库 [self.context save:nil]; } #pragma mark 查询数据 - (void)findData { // 初始化查询对象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"]; // 按照age降序 NSSortDescriptor *desc = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:NO]; request.sortDescriptors = [NSArray arrayWithObject:desc]; // 设置条件过滤 where age > 20 //request.predicate = [NSPredicate predicateWithFormat:@"age > %i", 20]; // name like '%j-1%' //request.predicate = [NSPredicate predicateWithFormat:@"name like %@", @"*j-1*"]; NSArray *array = [self.context executeFetchRequest:request error:nil]; for (NSManagedObject *person in array) { NSString *name = [person valueForKey:@"name"]; int age = [[person valueForKey:@"age"] intValue]; NSLog(@"name=%@,age=%i", name, age); } } #pragma mark 插入数据 - (void)addData { //[[NSManagedObject alloc] initWithEntity:<#(NSEntityDescription *)#> insertIntoManagedObjectContext:<#(NSManagedObjectContext *)#>]; for (int i = 0; i<10; i++) { // 初始化一个跟上下文关联的对象 NSManagedObject *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.context]; // 设置对象的属性 [person setValue:[NSNumber numberWithInt:20+i] forKey:@"age"]; NSString *name = [NSString stringWithFormat:@"mj-%i", i]; [person setValue:name forKey:@"name"]; } // 将所有跟上下文相关联的对象同步到数据库 [self.context save:nil]; } #pragma mark 初始化上下文对象 - (void)initContext { // 1.加载模型文件 // nil代表从应用程序主bundle里面加载模型文件 NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil] ; // 2.初始化持久化存储调度器 NSPersistentStoreCoordinator *store = [[[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model] autorelease]; // 添加持久化存储库(这里用数据库存储) NSString *path = [@"coredata.db" documentsAppend]; NSURL *url = [NSURL fileURLWithPath:path]; // 一定要给指针赋值 NSError *error = nil; [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:&error]; if (error) { NSLog(@"打开数据库失败:%@", [error localizedDescription]); return; } // 3.初始化上下文对象 self.context = [[[NSManagedObjectContext alloc] init] autorelease]; self.context.persistentStoreCoordinator = store; } @end
下面是面向模型
#import "ViewController.h" #import <CoreData/CoreData.h> #import "Person.h" #import "Car.h" @interface ViewController () @property(nonatomic,retain)NSManagedObjectContext *context; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. //从应用程序加载模型文件 NSManagedObjectModel *model=[NSManagedObjectModel mergedModelFromBundles:nil]; //传入模型对象,初始化NSPersistentStoreCoordinator对象 NSPersistentStoreCoordinator *psc=[[[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model] autorelease]; //构建sqlite数据库文件的路径 NSString *docs=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSURL *url=[NSURL fileURLWithPath:[docs stringByAppendingPathComponent:@"person.db"]]; NSError *error=nil; if (![psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:&error]) { //[NSException raise:@"创建数据库失败" format:@"%@",[error localizedDescription]]; NSLog(@"创建数据库失败-->%@",[error localizedDescription]); } self.context=[[NSManagedObjectContext alloc] init]; self.context.persistentStoreCoordinator=psc; [_context release]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (IBAction)addclick:(id)sender { Person *person=[NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.context]; person.name=@"gcb111"; person.age=@231; Car *car=[NSEntityDescription insertNewObjectForEntityForName:@"Car" inManagedObjectContext:self.context]; //[car setValue:@"123456789456" forKey:@"no"]; car.no=@"ssss111111"; car.person=person; NSError *error=nil; [self.context save:&error]; if(error){ NSLog(@"-->同步失败-->%@",error.localizedDescription); } else{ NSLog(@"--->同步成功-->"); } } - (IBAction)selectClick:(id)sender { //创建查询请求 NSFetchRequest *request=[[NSFetchRequest alloc] init]; //获取请求的实体 request.entity=[NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.context]; NSSortDescriptor *sort=[[NSSortDescriptor alloc] initWithKey:@"age" ascending:YES]; request.sortDescriptors=@[sort]; NSError *error=nil; NSArray *arr=[self.context executeFetchRequest:request error:&error]; if (error) { NSLog(@"-->查询失败-%@",error.localizedDescription); return; } for (Person *p in arr) { NSLog(@"-->%@-->%@",p.name,p.age); } } - (IBAction)UpdateClick:(id)sender { NSArray *arr=[self queryByAge:15]; for (Person *p in arr) { p.age=@16; } NSError *error=nil; [self.context save:&error]; if (error) { NSLog(@"-->失败-%@",error); } } - (IBAction)DelClick:(id)sender { NSArray *arr=[self queryByAge:16]; for (Person *p in arr) { [self.context deleteObject:p]; } NSError *error=nil; [self.context save:&error]; if (error) { NSLog(@"-->失败-%@",error); } } -(NSArray *)queryByAge:(int)age{ NSFetchRequest *request=[[NSFetchRequest alloc] init]; request.entity=[NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.context]; NSPredicate *predicate=[NSPredicate predicateWithFormat:@"age=%i",age]; request.predicate=predicate; NSError *error=nil; NSArray *arr=[self.context executeFetchRequest:request error:&error]; if (error) { NSLog(@"-->查询失败-%@",error.localizedDescription); return nil; } return arr; }