IOS CoreData (1)

来源:互联网 发布:北京纸箱厂 淘宝彩色 编辑:程序博客网 时间:2024/05/22 10:50

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时候的代码,理解了上述用到的一些类就可以进行基本的存取操作了。

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

 


<script type="text/javascript"><!--google_ad_client = "ca-pub-1944176156128447";/* cnblogs 首页横幅 */google_ad_slot = "5419468456";google_ad_width = 728;google_ad_height = 90;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
原创粉丝点击