CoreData学习

//第一种方法全部加载

//nil表示从主bundles中加载对应的模型实体,其实会把程序中得所有的实体都加载了

NSManagedObjectModel *model=[NSManagedObjectModel mergedModelFromBundles:nil];

for (NSEntityDescription *desc in model.entities) {

NSLog(@"%@",desc.name);

}

//第二种方法

//从应用程序包中加载模型文件

// NSURL *modelUrl= [[NSBundle mainBundle] URLForResource:@"Model" withExtension:@"momd"];

//    NSManagedObjectModel *model=[[NSManagedObjectModel alloc]initWithContentsOfURL:modelUrl];

//通过模型 和数据库持久化

NSPersistentStoreCoordinator *psc=[[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:model];

//持久化到coredata中

NSString *docs=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

NSURL *url=[NSURL fileURLWithPath:[docs stringByAppendingPathComponent:@"person.db"]];

NSError *error=nil;

NSPersistentStore *store=[psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url

options:nil error:&error];

if (store==nil) {

[NSException raise:@"添加数据库错误" format:@"%@",[error localizedDescription]];

}

NSManagedObjectContext *context=[[NSManagedObjectContext alloc]initWithConcurrencyType:NSMainQueueConcurrencyType];

context.persistentStoreCoordinator=psc;

NSManagedObject *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:context];

// 设置Person的简单属性

[person setValue:@"fengxin" forKey:@"name"];

[person setValue:[NSNumber numberWithInt:27] forKey:@"age"];

// 传入上下文,创建一个Card实体对象

NSManagedObject *card = [NSEntityDescription insertNewObjectForEntityForName:@"Card" inManagedObjectContext:context];

[card setValue:@"4414241933432" forKey:@"no"];

// 设置Person和Card之间的关联关系

[person setValue:card forKey:@"card"];

// 利用上下文对象,将数据同步到持久化存储库

NSError *error1 = nil;

BOOL success = [context save:&error1];

if (!success) {

[NSException raise:@"访问数据库错误" format:@"%@", [error1 localizedDescription]];

}


//下面是查询

NSFetchRequest *request=[NSFetchRequest fetchRequestWithEntityName:@"Person"];

NSArray *results= [context executeFetchRequest:request error:&error];

for (NSManagedObject *mode in results) {

NSLog(@"%@",mode);

}

你可能感兴趣的:(CoreData学习)