iOS

iOS-CoreData数据持久化

2016-11-09  本文已影响5人  和谐共处

1.NSManagedObjectContext的创建

  - (NSManagedObjectContext *)creatManagedObjectContext
{
    //1、创建模型对象
    //获取模型路径
    //modelName 模型名字(带xcdatamodeld后缀的名字)
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"modelName" withExtension:@"momd"];
    //根据模型文件创建模型对象
    NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    //2、创建持久化助理    //利用模型对象创建助理对象
    NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
    //数据库的名称和路径
    NSString *docStr = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *sqlPath = [docStr stringByAppendingPathComponent:@"mySqlite.sqlite"];    NSLog(@"path = %@", sqlPath);
    NSURL *sqlUrl = [NSURL fileURLWithPath:sqlPath];
    //设置数据库相关信息
    [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:sqlUrl options:nil error:nil];
    //3、创建上下文
    NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    //关联持久化助理
    context.persistentStoreCoordinator = store;
    
    return context;
    
}

2.对Entity(实体)的操作

查询
  #pragma mark - 查询
- (void)queryData:(id)data
{

    NSError *error = nil;
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Book"];
    
    NSMutableArray *resultArray = [[_myAppdelegate.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
    if (resultArray == nil) {
        NSLog(@"error = %@",error);
    }else{
        NSLog(@"query successful!");
    }
    
    for (Book *book in resultArray) {
        NSLog(@"name==%@------price==%@\n",book.name,book.price);
    }
}
插入
   #pragma mark - 插入
- (void)insertData:(id)data
{
    Book *book = [NSEntityDescription insertNewObjectForEntityForName:@"Book" inManagedObjectContext:_myAppdelegate.managedObjectContext];
    book.name = @"软件开发";
    book.price = [NSNumber numberWithFloat:10.5];
    
    NSError *error = nil;
    
    BOOL isSaveSuccess = [_myAppdelegate.managedObjectContext save:&error];
    if (!isSaveSuccess) {
        NSLog(@"Error:%@",error);
    }else{
        NSLog(@"Save successful!");
    }
    
}
删除
   #pragma mark - 删除
- (void)deleteData:(id)date
{
    NSFetchRequest *request = [[NSFetchRequest alloc]init];
    
    NSEntityDescription *book = [NSEntityDescription entityForName:@"Book" inManagedObjectContext:_myAppdelegate.managedObjectContext];
    request.entity = book;
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name==%@",@"我的青春"];
    request.predicate = predicate;
    
    NSError *error = nil;
    
    NSMutableArray *fetchResult = [[_myAppdelegate.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
    if (fetchResult == nil) {
        NSLog(@"delete error = %@",error);
    }else{
        NSLog(@"delete successful!");
    }
    for (Book *book in fetchResult) {
        [_myAppdelegate.managedObjectContext deleteObject:book];
    }
    if (![_myAppdelegate.managedObjectContext save:&error]) {
        NSLog(@"Error == %@,%@",error,error.userInfo);
    }else{
        NSLog(@"delete save successful !");
    }
}
更新
    #pragma mark - 更新
- (void)updateData:(id)data
{
    NSFetchRequest *request = [[NSFetchRequest alloc]init];
    
    NSEntityDescription *book = [NSEntityDescription entityForName:@"Book" inManagedObjectContext:_myAppdelegate.managedObjectContext];
    request.entity = book;
    //条件
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name==%@",@"软件开发"];
    request.predicate = predicate;
    
    NSError *error = nil;
    
    NSMutableArray *fetchResult = [[_myAppdelegate.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
    if (fetchResult == nil) {
        NSLog(@"Error= %@",error);
    }else{
        NSLog(@"update successful!");
    }
    
    for (Book *book in fetchResult) {
        book.name = @"我的青春";
    }
    [_myAppdelegate.managedObjectContext save:&error];
    
}
上一篇 下一篇

猜你喜欢

热点阅读