添加 core data 支持 ios 项目

网上很多教程包括apple自己的都是从一个core data的模板项目教起, 没有一个怎么在既有的项目上添加core data的方法(也许有,反正我没找到), 下面就是自己研究的添加core data的步骤, 我用的是mac os x 10.6.7, xcode4.0.0

 

 

1.  添加core data framework 

xcode中选中项目根,在右边的面板中选中targets下面的项目名,再在右边选中 Build Phases, 再选中Link Binary with Libraries,  点加号添加core data 框架

 

   在项目中找一个xx.pch的文件, 加上一行 #import <CoreData/CoreData.h>

 

2. 在项目的XXXAppDelegate.h 文件中 加入

 

C代码   收藏代码
  1. @property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;  
  2. @property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;  
  3. @property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;  
  4.   
  5.   
  6. - (void)saveContext;  
  7. - (NSURL *)applicationDocumentsDirectory;  
 

XXXAppDelegate.m文件中加入

 

 

C代码   收藏代码
  1. @synthesize managedObjectContext=__managedObjectContext;//session  
  2.   
  3. @synthesize managedObjectModel=__managedObjectModel;  
  4.   
  5. @synthesize persistentStoreCoordinator=__persistentStoreCoordinator;  
  6.   
  7.   
  8.   
  9. //相当与持久化方法  
  10. - (void)saveContext  
  11. {  
  12.     NSError *error = nil;  
  13.     NSManagedObjectContext *managedObjectContext = self.managedObjectContext;  
  14.     if (managedObjectContext != nil)  
  15.     {  
  16.         if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error])  
  17.         {  
  18.             /* 
  19.              Replace this implementation with code to handle the error appropriately. 
  20.               
  21.              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. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button. 
  22.              */  
  23.             NSLog(@"Unresolved error %@, %@", error, [error userInfo]);  
  24.             abort();  
  25.         }   
  26.     }  
  27. }  
  28.   
  29.   
  30. #pragma mark - Core Data stack  
  31.   
  32. /** 
  33.  Returns the managed object context for the application. 
  34.  If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application. 
  35.  */  
C代码   收藏代码
  1. //初始化context对象  
C代码   收藏代码
  1. - (NSManagedObjectContext *)managedObjectContext  
C代码   收藏代码
  1. {  
  2.     if (__managedObjectContext != nil)  
  3.     {  
  4.         return __managedObjectContext;  
  5.     }  
  6.       
  7.     NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];  
  8.     if (coordinator != nil)  
  9.     {  
  10.         __managedObjectContext = [[NSManagedObjectContext alloc] init];  
  11.         [__managedObjectContext setPersistentStoreCoordinator:coordinator];  
  12.     }  
  13.     return __managedObjectContext;  
  14. }  
  15.   
  16. /** 
  17.  Returns the managed object model for the application. 
  18.  If the model doesn't already exist, it is created from the application's model. 
  19.  */  
  20. - (NSManagedObjectModel *)managedObjectModel  
  21. {  
  22.     if (__managedObjectModel != nil)  
  23.     {  
  24.         return __managedObjectModel;  
  25.     }  
C代码   收藏代码
  1. //这里的URLForResource:@"lich" 的url名字(lich)要和你建立datamodel时候取的名字是一样的,至于怎么建datamodel很多教程讲的很清楚  
  2.     NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"lich" withExtension:@"momd"];  
  3.     __managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];      
  4.     return __managedObjectModel;  
  5. }  
  6.   
  7. /** 
  8.  Returns the persistent store coordinator for the application. 
  9.  If the coordinator doesn't already exist, it is created and the application's store added to it. 
  10.  */  
  11. - (NSPersistentStoreCoordinator *)persistentStoreCoordinator  
  12. {  
  13.     if (__persistentStoreCoordinator != nil)  
  14.     {  
  15.         return __persistentStoreCoordinator;  
  16.     }  
  17.     //这个地方的lich.sqlite名字没有限制,就是一个数据库文件的名字  
  18.     NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"lich.sqlite"];  
  19.       
  20.     NSError *error = nil;  
  21.     __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];  
  22.     if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])  
  23.     {  
  24.         /* 
  25.          Replace this implementation with code to handle the error appropriately. 
  26.           
  27.          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. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button. 
  28.           
  29.          Typical reasons for an error here include: 
  30.          * The persistent store is not accessible; 
  31.          * The schema for the persistent store is incompatible with current managed object model. 
  32.          Check the error message to determine what the actual problem was. 
  33.           
  34.           
  35.          If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory. 
  36.           
  37.          If you encounter schema incompatibility errors during development, you can reduce their frequency by: 
  38.          * Simply deleting the existing store: 
  39.          [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil] 
  40.           
  41.          * Performing automatic lightweight migration by passing the following dictionary as the options parameter:  
  42.          [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil]; 
  43.           
  44.          Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details. 
  45.           
  46.          */  
  47.         NSLog(@"Unresolved error %@, %@", error, [error userInfo]);  
  48.         abort();  
  49.     }      
  50.       
  51.     return __persistentStoreCoordinator;  
  52. }  
  53.   
  54. #pragma mark - Application's Documents directory  
  55.   
  56. /** 
  57.  Returns the URL to the application's Documents directory. 
  58.  */  
  59. - (NSURL *)applicationDocumentsDirectory  
  60. {  
  61.     return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];  
  62. }  

 

因为加入了新的属性,自己记得去release

 

这里比较奇怪的一点是RLForResource:@"lich" withExtension:@"momd"]; 扩展名是momd 而不是xcdatamodeld,原因可能是:

xcdatamodeld文件是编译前的状态,这个文件在编译时会被转为momd文件被拷贝到App的main bundle里

 

上面很多代码是从core data模板项目里copy过来的,大致的意思就是先建立一个managedObjectModel,

然后根据 managedObjectModel 建立 persistentStoreCoordinator

然后根据 persistentStoreCoordinator 建立 managedObjectContext

 

3. 然后是把managedObjectContext传给真正要使用数据的 viewcontroller

 

 

Java代码   收藏代码
  1. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  
  2. {  
  3.    // NSLog(@"%@===================", [self applicationDocumentsDirectory]);  
  4.     [self.window makeKeyAndVisible];  
  5.     NSManagedObjectContext *context = [self managedObjectContext];  
  6.     NSArray *array =  self.tabBarController.viewControllers;  
  7.     for (UINavigationController *navi in array) {  
  8.         RootView *rv = (RootView *)navi.topViewController;  
  9.         rv.context = context;  
  10.     }  
 

我开始不明白为什么要在XXXAppDelegate中建立managedObjectContext 而不是在viewcontroller中,那样就不用传来传去了啊

也许是view对象有时候会被销毁吧

转自:http://www.iteye.com/topic/1017633

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值