CoreData简单入门

CoreData是iOS5之后出的数据化存储框架,缓存本地化内容,提高应用程序响应速度,实际使用过程中也非常简单,提供了数据建模工具,可视化对象图表的方式提供一对一,一对多,多对多的数据关系,通过Model和Context实现数据增删改查。CoreData经过苹果的优化,无论在是单元测试还是运行速度上都是非常优秀的,有必要进行一下简单的入门了解.

新增

CoreData简单入门_第1张图片
Snip20160405_1.png
    Book *insertBook=[NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass([Book class]) inManagedObjectContext:self.context];
    if (self.textField.text.length) {
        insertBook.author=self.textField.text;
        [self.dataManger saveContext];
        NSLog(@"FlyElephant add data--%@",self.textField.text);
    }

查询

    if (self.textField.text.length) {
        NSFetchRequest *request =[[NSFetchRequest alloc] init];
        request.entity = [NSEntityDescription entityForName:NSStringFromClass([Book class]) inManagedObjectContext:self.context];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"author contains %@", self.textField.text];
        request.predicate = predicate;
        NSError *error = nil;
        NSArray *objs = [self.context executeFetchRequest:request error:&error];
        if (error) {
            [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
        }
        for (NSManagedObject *obj in objs) {
            NSLog(@"作者=%@", [obj valueForKey:@"author"]);
        }
        NSLog(@"search success-FlyElephant");
    }

更新

    if (self.textField.text.length) {
        NSFetchRequest *request =[[NSFetchRequest alloc] init];
        request.entity = [NSEntityDescription entityForName:NSStringFromClass([Book class]) inManagedObjectContext:self.context];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"author like %@", self.textField.text];
        request.predicate = predicate;
        NSError *error = nil;
        NSArray *objs = [self.context executeFetchRequest:request error:&error];
        if (error) {
            [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
        }
        for (NSManagedObject *obj in objs) {
            NSLog(@"FlyElephant author=%@", [obj valueForKey:@"author"]);
            NSString *updateValue=[NSString stringWithFormat:@"%@修改",[obj valueForKey:@"author"]];
            [obj  setValue:updateValue forKey:@"author"];
        }
        [self.dataManger saveContext];
    }

删除

    if (self.textField.text.length) {
        NSFetchRequest *request =[[NSFetchRequest alloc] init];
        request.entity = [NSEntityDescription entityForName:NSStringFromClass([Book class]) inManagedObjectContext:self.context];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"author contains %@", self.textField.text];
        request.predicate = predicate;
        NSError *error = nil;
        NSArray *objs = [self.context executeFetchRequest:request error:&error];
        if (error) {
            [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
        }
        for (NSManagedObject *obj in objs) {
            NSLog(@"作者=%@", [obj valueForKey:@"author"]);
            [self.context deleteObject:obj];
        }
        [self.dataManger saveContext];
    }else{
        NSFetchRequest *request =[[NSFetchRequest alloc] init];
        request.entity = [NSEntityDescription entityForName:NSStringFromClass([Book class]) inManagedObjectContext:self.context];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"author != ''"];
        request.predicate = predicate;
        NSError *error = nil;
        NSArray *objs = [self.context executeFetchRequest:request error:&error];
        if (error) {
            [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
        }
        for (NSManagedObject *obj in objs) {
            NSLog(@"作者=%@", [obj valueForKey:@"author"]);
            [self.context deleteObject:obj];
        }
        [self.dataManger saveContext];
    }
    NSLog(@"delete success-FlyELephant");

以上的增删改查是根据FEDataManger进行操作的,FEDataManger的代码:

-(NSManagedObjectContext *)managedObjectContext{
    if (!_managedObjectContext) {
        NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
        
        //初始化NSPersistentStoreCoordinator
        NSPersistentStoreCoordinator *persistCoordinator=[[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:model];
        NSURL *applicationURL=[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
        NSURL *storeURL = [applicationURL URLByAppendingPathComponent:@"FECoreData.sqlite"];
        
        NSError *error = nil;
        NSPersistentStore *store = [persistCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error];
        if (store == nil) {
            [NSException raise:@"添加数据库错误" format:@"%@", [error localizedDescription]];
        }
        _managedObjectContext=[[NSManagedObjectContext alloc]initWithConcurrencyType:NSMainQueueConcurrencyType];
        _managedObjectContext.persistentStoreCoordinator = persistCoordinator;
    }
    return _managedObjectContext;
}

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            NSLog(@"保存错误 %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

项目地址

FECoreData传送门-FlyElephant

你可能感兴趣的:(CoreData简单入门)