博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
关于CoreData的用法
阅读量:5175 次
发布时间:2019-06-13

本文共 5511 字,大约阅读时间需要 18 分钟。

有些同事觉得CoreData是一个看不懂,理解不清的神秘东东,其实ios的本地数据储存是一个sqlite数据库,一个简易的数据库,而这个CoreData是否支持所有储存的数据呢,显然不是的,站在我的角度,我是不支持把一些图片数据保存的CoreData里面,其一,如果保存图片需要把图片转化为Data类型,

    UIImage * image = info[UIImagePickerControllerEditedImage];
    //把Image转化成Data
    self.imageData = UIImagePNGRepresentation(image);
其二,不具有稳定性。下面给大家讲解下CoreData的用法。
1.如果大家现在用Storyboard的,可以在建项目时选择在Use Core Data处打勾。

 

如果你是用纯代码写程序的话,那么你需要手动在AppDelegate里面写上这些代码

.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 *)applicationDocumentsDirectory;
@end

.m

- (void)saveContext

{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
             // Replace this implementation with code to handle the error appropriately.
             // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}
#pragma mark - Core Data stack
// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
- (NSManagedObjectContext *)managedObjectContext
{
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        _managedObjectContext = [[NSManagedObjectContext alloc] init];
        [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return _managedObjectContext;
}
// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
- (NSManagedObjectModel *)managedObjectModel
{
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"App_7_addressbook" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}
// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"App_7_addressbook.sqlite"];
    
    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
                NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }    
    
    return _persistentStoreCoordinator;
}
#pragma mark - Application's Documents directory
// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
这些就是需要建立cordata的根本,不需要你的理解。接下来我们就应该建立一个实体,对cordata不熟悉的技术人员也许疑问为什么简历实体?其实我们储存和获取数据没有对cordata直接操作,而是对实体进行操作。

 

 

 

创建一个model,这就是实体的,然后我们再创建一个实体类:

 

创建意识实体对象,然后生成一个实体类:

 

下面我们就对实体进行操作:

 

@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;

通过managedObjectContext进行储存操作,

 首先对managedObjectContext进行初始化;

    UIApplication * app = [UIApplication sharedApplication];
    id delegate = [app delegate];
    self.managedObjectContext = [delegate managedObjectContext];

1.然后在保存地方进行往coredata储存,

如:      

self.p.number = self.numberT.text;

self.p.image = self.imageData;

NSError * error;

        if (![self.managedObjectContext save:&error]) {
            NSLog(@"新建保存错误:%@",[error localizedDescription]);
        }
进行保存。

2.在你从coredata获取数据的Controller写,

@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;

@property(nonatomic,strong)NSFetchedResultsController * fetchedResultsController;

 

这里的fetchedResultsController是从coredata获取数据,

- (void)viewDidLoad {

    [super viewDidLoad];
    
    UIApplication *application = [UIApplication sharedApplication];
    id delegate = application.delegate;
    self.managedObjectContext = [delegate managedObjectContext];
    
    /*********
     通过CoreData获取sqlite中的数据
     *********/
    
    //通过实体名获取请求
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:NSStringFromClass([Time class])];
    
    //定义分组和排序规则
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"timego" ascending:NO];
    
    //把排序和分组规则添加到请求中
    [request setSortDescriptors:@[sortDescriptor]];
    
    //把请求的结果转换成适合tableView显示的数据
    self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
    
    
    //执行fetchedResultsController
    NSError *error;
    if ([self.fetchedResultsController performFetch:&error]) {
        NSLog(@"%@", [error localizedDescription]);
    }
    self.fetchedResultsController.delegate = self;
}

这些就是coredata基本简单用法,代码没有过多写,重要核心就是这些了

 

转载于:https://www.cnblogs.com/hanguoqing/p/4431644.html

你可能感兴趣的文章
CLR:基元类型、引用类型和值类型
查看>>
dubbo序列化hibernate.LazyInitializationException could not initialize proxy - no Session懒加载异常的解决...
查看>>
jQuery中的事件绑定的几种方式
查看>>
泥塑课
查看>>
setImageBitmap和setImageResource
查看>>
springMVC4 注解配置实例
查看>>
单片机编程
查看>>
Filter in Servlet
查看>>
Linux--SquashFS
查看>>
Application Pool Identities
查看>>
2017-3-24 开通博客园
查看>>
【MySQL性能优化】MySQL常见SQL错误用法
查看>>
Vue2全家桶之一:vue-cli(vue脚手架)超详细教程
查看>>
Struts 2 常用技术
查看>>
树形DP
查看>>
python flask解决上传下载的问题
查看>>
语法测试
查看>>
CES1
查看>>
java webcontroller访问时报415错误
查看>>
qcow2、raw、vmdk等镜像格式
查看>>