xcode中coredata的存储文件怎么找

xcode中coredata的存储文件怎么找,第1张

1.Core Data 是数据持久化存储的最佳方式

2.数据最终的存储类型可以是:SQLite数据库,XML,二进制,内存里,或自定义数据类型

在Mac OS X 10.5Leopard及以后的版本中,开发者也可以通册陪过继承NSPersistentStore类以创建自定义的存储格式

3.好处:能够合理管理内存,避免使用sql的麻烦,高效

4.构成:

(1)NSManagedObjectContext(被管理的数据上下文)

*** 肆姿桥作实际内容( *** 作持久层)

作用:插入数据,查询数据,删除数据

(2)NSManagedObjectModel(被管理的数据模型)

数据库所有表格或数据结构,包含各实体的定义信息

作用:添加实体的属性,建立属性之间的关系

*** 作方法:视图编辑器,或代码

(3)NSPersistentStoreCoordinator(持久化存储助理)

相当于数据库的连接器

作用:设置数据存储的名字,位置,裂猛存储方式,和存储时机

(4)NSManagedObject(被管理的数据记录)

相当于数据库中的表格记录

(5)NSFetchRequest(获取数据的请求)

相当于查询语句

(6)NSEntityDescription(实体结构)

相当于表格结构

(7)后缀为.xcdatamodeld的包

里面是.xcdatamodel文件,用数据模型编辑器编辑

编译后为.momd或.mom文件

Core Data 简介并虚

• Core Data 是 iOS SDK 里的一个很强大的框架,允许程序员 以面向对象 的方链蔽局式储存和管理数据 。使用 Core Data 框架,程序员可以很轻松有效 地通过面向对象的接口管理数据

• Core Data 框架提供棚让了 对象 - 关系映射 (ORM) 的功能,即能够将 OC 对象转 化成数据,保存在 SQLite3 数据库文件中,也能够将保存在数据库中的 数据还原成 OC 对象

• 在数据 *** 作过程中,无需编写任何 SQL 语句

• 要使用 Core Data , 需要导入 CoreData 框架

第一步:创建一个 DataDemo.xcdatamodel 文件,在其中建一个实体名字为 Entity1 ,实体中建袭睁两个字段 id 和 name。

第二步:为项目添拍则岁加 CoreData.framework 框架,然后在 .pch 中加入盯胡 #import <coredata/coredata.h>

第三步:在 app delegate 中定义 core data 的相关对象(同时完成它们的初始化工作)

.h 文件:

#import <coredata/coredata.h>

@private

NSManagedObjectModel *managedObjectModel

NSManagedObjectContext *managedObjectContext

NSPersistentStoreCoordinator *persistentStoreCoordinator

@property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel

@property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext

@property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator

- (NSString*) applicationDocumentsDirectory

- (void) saveContext

.m 文件:

@synthesize managedObjectModel

@synthesize managedObjectContext

@synthesize persistentStoreCoordinator

- (void)dealloc {

[managedObjectModel release]

[managedObjectContext release]

[persistentStoreCoordinator release]

[super dealloc]

}

- (NSString*)applicationDocumentsDirectory

{

//return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)

NSString *basePath = ([paths count] >0) ? [paths objectAtIndex:0] : nil

return basePath

//return [NSURL URLWithString:basePath]

}

- (void)saveContext{

NSError *error = nil

NSManagedObjectContext *objectContext = self.managedObjectContext

if (objectContext != nil)

{

if ([objectContext hasChanges] &&![objectContext save:&error])

{

NSLog(@"Unresolved error %@, %@", error, [error userInfo])

abort()

}

}

}

- (NSManagedObjectContext *)managedObjectContext

{

if (managedObjectContext != nil) {

return managedObjectContext

}

NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]

if (coordinator != nil) {

managedObjectContext = [[NSManagedObjectContext alloc] init]

[managedObjectContext setPersistentStoreCoordinator:coordinator]

}

return managedObjectContext

}

- (NSManagedObjectModel *)managedObjectModel

{

if (managedObjectModel != nil) {

return managedObjectModel

}

//从本地所有 xcdatamodel 文件中获得这个 CoreData 的数据模板

managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain]

return managedObjectModel

}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator

{

if (persistentStoreCoordinator != nil) {

return persistentStoreCoordinator

}

//数据库名为TestDB.sqlite

NSURL *storeUrl = [NSURL fileURLWithPath:[[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"TestDB.sqlite"]]

NSError *error

persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]

if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nilURL:storeUrl options:nil error:&error]) {

NSAssert(0, @"persistentStoreCoordinator init failed!")

}

return persistentStoreCoordinator

}

- (void)applicationWillTerminate:(UIApplication *)application

{

NSError *error

if (managedObjectContext != nil) {

if ([managedObjectContext hasChanges] &&![managedObjectContext save:&error]) {

NSAssert(0, @"save changes failed when terminage application!")

}

}

}

第四步:在相关的 viewcontroller 中 *** 作数据,基本的 core data *** 作代码如下:

NSError *error

testSQLiteAppDelegate *app = (testSQLiteAppDelegate*)[[UIApplication sharedApplication] delegate]

NSManagedObjectContext *context = app.managedObjectContext

//1、插入

NSManagedObject *newManagedObject = nil

newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:@"Entity1" inManagedObjectContext:context]

[newManagedObject setValue:[NSNumber numberWithInt:1] forKey:@"id"]

[newManagedObject setValue:@"i love you" forKey:@"name"]

if (![context save:&error]){

NSLog (@"The error is: %@", [error userInfo])

}

else

{

NSLog (@"The newManagedObject's id is: %@", [newManagedObject valueForKey:@"id"])

}

//2、查询

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Entity1" inManagedObjectContext:context]

NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc] initWithKey:@"id" ascending:YES]

NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]

NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor1, sortDescriptor2, nil]

[fetchRequest setSortDescriptors:sortDescriptors]

[fetchRequest setEntity:entity]

[fetchRequest setFetchBatchSize:20]

NSArray *objects = [context executeFetchRequest: fetchRequest error:&error]

if (objects == nil)

{

NSLog(@"There was an error!")

}

else {

for (NSManagedObject *oneObject in objects)

{

NSLog(@"%@",[oneObject valueForKey:@"name"])

}

}

//3、删除

[context deleteObject:[objects objectAtIndex:0]]

if (![context save:&error]) {

exit(-1)

}

这里更详细的补充一点关于 core data 的 *** 作代码:

1、条件过滤:选择 cid=1 的数据

- (NSFetchedResultsController*) fetchedResultsController

{

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"cid=1"]

[fetchRequest setPredicate:predicate]

}

2、通用代码,在 viewcontroller 里面会用到:

TestViewController.h 的代码:

@interface TestViewController : UITableViewController <NSFetchedResultsControllerDelegate>

{

NSFetchedResultsController *fetchedResultsController

NSManagedObjectContext *managedObjectContext

}

@property (nonatomic, retain) NSFetchedResultsController *fetchedResultsController

@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext

- (void)configureCell:(UITableViewCell *)cell withCategory:(Category *)category

@end

TestViewController.m 的代码:

-(NSFetchedResultsController *)fetchedResultsController

{

if (fetchedResultsController != nil)

{

return fetchedResultsController

}

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Category" inManagedObjectContext:managedObjectContext]

[fetchRequest setEntity:entity]

NSSortDescriptor *nameDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]

NSArray *arraySortDescriptor = [[NSArray alloc] initWithObjects:nameDescriptor, nil]

[fetchRequest setSortDescriptors:arraySortDescriptor]

NSPredicate *predicate = [NSPredicate predicateWithFormat:cidString]

[fetchRequest setPredicate:predicate]

NSFetchedResultsController *frController = [[NSFetchedResultsController alloc]

initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:@"name" cacheName:@"Root"]

frController.delegate = self

self.fetchedResultsController = frController

[frController release]

[fetchRequest release]

[nameDescriptor release]

return fetchedResultsController

}

- (void)controllerWillChangeContent:(NSFetchedResultsController *)

{

[self.tableView beginUpdates]

}

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject

atIndexPath:(NSIndexPath *)indexPath forChangeType: (NSFetchedResultsChangeType)type

newIndexPath:(NSIndexPath *)newIndexPath

{

UITableView *tableView = self.tableView

switch (type) {

case NSFetchedResultsChangeInsert:

[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade]

break

case NSFetchedResultsChangeDelete:

[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]

break

case NSFetchedResultsChangeMove:

[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]

[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade]

break

case NSFetchedResultsChangeUpdate:

[self configureCell:[tableView cellForRowAtIndexPath:indexPath] withCategory:anObject]

break

default:

break

}

}

- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo

atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type

{

switch(type) {

case NSFetchedResultsChangeInsert:

[self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade]

break

case NSFetchedResultsChangeDelete:

[self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade]

break

}

}

- (void) controllerDidChangeContent:(NSFetchedResultsController *)controller

{

[self.tableView endUpdates]

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/12241466.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-22
下一篇 2023-05-22

发表评论

登录后才能评论

评论列表(0条)

保存