iOS7应用开发12:Core Data

来源:互联网 发布:三星手机未网络上注册 编辑:程序博客网 时间:2024/05/29 18:36

Core Data:一种数据库机制,可以用于保存应用中需要永久保存的数据,是一种面向对象的数据库,在ios中应用极为广泛。


应用方法:

(1)在xcode中建立一个visual mapping,即在新建文件中选择Core Data->Data Model。在Data Model文件中添加Entity,在Entity中添加attribute并设置类型。各个entity可以通过ctrl+拖动建立relation,并在右侧栏中设置relation的属性。

(2)另一种方式:通过NSManagedObjectContext——建立UIManagedDocument,并获取managedObjectContext属性;需在创建工程时选择“Use Core Data”。


UIManagedDocument:该类是UIDocument的派生类,提供了大量的数据保存相关的方法,可方便适应iCloud的应用;可视为Core Data数据库的简单容器;

* 创建UIManagedDocument对象

NSFileManager *fileManager = [NSFileManager defaultManager];NSURL *documentsDirectory = [[fileManager URLsForDirectory:NSDocumentDirectoryinDomains:NSUserDomainMask] firstObject];! NSURL *url = [documentsDirectory URLByAppendingPathComponent:documentName];UIManagedDocument *document = [[UIManagedDocument alloc] initWithFileURL:url];

* 如何判断UIManagedDocument所关联的文件是否存在:

BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:[url path]];
* 若文件存在,打开文件:

[document openWithCompletionHandler:^(BOOL success){/*blocks to excute when open*/}];
* 若不存在:创建文件:

[document saveToURL:url forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success){/*blocks to execute when create is done*/}]
 由于打开/保存是异步操作所以必须采用completionHandler进行结束后的操作。

* 使用保存的文件之前检测状态:self.document.documentState == UIDocumentStateNormal;

* 关闭文件:如果没有强引用指针指向,则会自动关闭;手动关闭使用closeWithCompletionHandler:方法;


Core Data的操作:

1、向数据库中添加对象:

NSManagedObjectContext *context = aDocument.managedObjectContext;NSMagedObject *photo = [NSEntityDescription insertNewObjectForEntityForName:@"ObjName" inMagagedObjectContext:context];
2、获取NSManagedObject对象中的attribute:采用NSKeyValueCoding协议中的两个方法:

- (id)valueForKey:(NSString *)key;- (void)setValue:(id)value forKey:(NSString *)key;
其中key是data mapping中的attribute name,value是数据库中保存的数据。
更优方法:

建立NSManagerObject类的派生类:选中data model中的entity,在editor中选择Create subclass;完成后将为每一个entity建立头文件和源文件;
然后1中的添加操作就可以用下列语句表示:

NSManagedObjectContext *context = document.managedObjectContext;Photo *photo = [NSEntityDescription insertNewObjectForEntityForName:@“Photo” inManagedObjectContext:context];// then set the attributes in our Photo using, say, an NSDictionary we got from Flickr ...! e.g. photo.title = [flickrData objectFor//Key:FLICKR_PHOTO_TITLE];!// the information will automatically be saved (i.e. autosaved) into our document by Core Data// now here’s some other things we could do too ...!NSString *myThumbnail = photo.thumbnailURL; !photo.lastViewedDate = [NSDate date]; !photo.whoTook = ...; // a Photographer object we created or got by queryingphoto.whoTook.name = @“CS193p Instructor”; // yes, multiple dots will follow relationships!
3、在数据库中删除记录
[aDocument.managedObjectContext deleteObject:photo];


#分类category

category在第8篇中已经有过简单介绍,这里不再过多费口舌了。

需要强调的一点是,category的函数在实现的过程中不能使用局部变量。

【好累啊……%>_<%】


原创粉丝点击