• IOS CoreData


    IOS CoreData

    IOS 开发中经常会用CoreData,CoreData实际上使用的是SQLLite。今天开始看了看CoreData的基本使用,记录一下学习过程与体会。

      在CoreData中有几个概念要清楚Model,Entity,,Attribute,Relationship。可以简单的用关系数据库的概念来解释:model为database,Entity对应一张表,Attribute为表中的字段,relationship为关系。

      明白概念以后来看看使用CoreData的具体步骤:

      1,在项目中新建一个模型文件(Data Model),新建后项目里面会有一个*.xcdatamodeld文件生成。

      2,根据需求在模型中添加Entity,也就是我们理解的表。同时为Entity定义相应的Attribute。

      3,确立Entity之间的关系,支持一对一和一对多关系

      4,为每个Entity添加对应的NSManagedObject子类,实现数据存取操作

      前3步都可以在可视化额界面下完成,第4需要自己写代码去实现。

      

      在写代码之前需要了解CoreData里面几个重要对象:

      NSManagedObject:通过CoreData取回的对象默认都是NSManagedObject,所以使用Core Data的Entity类都是继承自NSManagedObject。(可以在Model中新建Entity后由在xcode中新建NSManagedObject subclass由xcode自动生成对应子类)

      NSManagedObjectContext:负责应用和数据库之间的工作

      NSPersistantStoreCoordinator:可以指定文件并打开相应的SQLLite数据库。

      NSFetchRequest:用来获取数据

      NSEntityDesciption:代表Entity 对应的类

       有了这些类基本就可以开始写自己的的代码了:

     初始化需要用到的类实例:

    复制代码
    - (id)init
    {
        self=[super init];
        
        if(self != nil)
        {
            //读取model文件
            model = [NSManagedObjectModel mergedModelFromBundles:nil];
            
            NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
            
            //设置SQLLite path
            NSString *path = [self noteArchivePath];
            NSURL *storeURL = [NSURL fileURLWithPath:path];
            
            NSError *error = nil;
            
            if([psc addPersistentStoreWithType:NSSQLiteStoreType
                                 configuration:nil
                                           URL:storeURL
                                       options:nil
                                         error:&error] == nil
               )
            {
                [NSException raise:@"Open failed" format:@"Reason: %@",[error localizedDescription]];
            }
            
            //创建NSManagedObjectContext对象
            context = [[NSManagedObjectContext alloc] init];
            [context setPersistentStoreCoordinator:psc];
            
            [context setUndoManager:nil];
        }
        return self ;
    }
    复制代码

    利用NSFetchRequest获取数据库中的数据:

    复制代码
    - (NSUInteger)loadAllNotes
    {
        if(!allNotes)
        {
            NSFetchRequest *request = [[NSFetchRequest alloc] init];
            NSEntityDescription *e = [[model entitiesByName] objectForKey:@"NoteItem"] ;
            [request setEntity:e];
            
            NSError *error=nil;
            
            NSArray *result = [context executeFetchRequest:request error:&error] ;
            
            if(result == nil)
            {
                [NSException raise:@"Fetch failed" format:@"Reason: %@",[error localizedDescription]];
            }
            
            allNotes = [[NSMutableArray alloc] initWithArray:result];
        }
        
            return allNotes.count;
        
    }
    复制代码

    对应Entity的类只能通过context来创建:

    复制代码
    - (NoteItem *)createNoteItem
    {
        NoteItem *note = [NSEntityDescription insertNewObjectForEntityForName:@"NoteItem" inManagedObjectContext:context];
        [allNotes addObject:note];
        return note ;
    }
    复制代码

    将数据保存到数据库中只要调用context中的对应方法就可以了:

    复制代码
    - (BOOL)saveChanges
    {
        NSError *error = nil ;
        
        BOOL successful = [context save:&error];
        
        if(!successful)
        {
            NSLog(@"Error saving %@",[error localizedDescription]);
        }
        
        return successful;
    }
    复制代码

    删除:

    - (void)removeNoteItem:(NoteItem *)note
    {
        [context deleteObject:(NSManagedObject *)note];
        [allNotes removeObject:note];
        
    }

    这些我写一个小dome时候的代码,理解了上述用到的一些类就可以进行基本的存取操作了。

    学习笔记,可能存在错误,仅供参考,欢迎指正。

     
     
     
    标签: IOS
  • 相关阅读:
    tableView小细节
    iOS5 切换中文键盘时覆盖输入框的解决方案
    NSBundle读取txt文件,图片,plist
    iOS OC 字符串处理
    图片拉伸 几种方式
    UIAlertView小结
    新来报道
    VC6.0之Debug调试总结
    关于C++中的临时对象问题
    与临时对象的斗争(下)
  • 原文地址:https://www.cnblogs.com/Leo_wl/p/3218803.html
Copyright © 2020-2023  润新知