关于Core Data的一些整理(一)

在Xcode7.2中只有Mast-Debug和Single View中可以勾选Use Core Data

如果勾选了Use Core Data,Xcode会自动在AppDelegate中帮你生成Core Data的核心代码,并且自动生成.xcdatamodeld数据文件
 
 //Appdelegate.h中
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator; - (void)saveContext;
- (NSURL *)applicationDocumentsDirectory; @end //Appdelegate.m中系统帮助生成的代码
- (void)applicationWillTerminate:(UIApplication *)application {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
[self saveContext];
} #pragma mark - Core Data stack @synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator; - (NSURL *)applicationDocumentsDirectory {
// The directory the application uses to store the Core Data store file. This code uses a directory named "qq100858433.JMHitList" in the application's documents directory.
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
} - (NSManagedObjectModel *)managedObjectModel {
// The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"JMHitList" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
} - (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
} // Create the coordinator and store _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"JMHitList.sqlite"];
NSError *error = nil;
NSString *failureReason = @"There was an error creating or loading the application's saved data.";
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
// Report any error we got.
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
dict[NSLocalizedFailureReasonErrorKey] = failureReason;
dict[NSUnderlyingErrorKey] = error;
error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code: userInfo:dict];
// Replace this with code to handle the error appropriately.
// 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.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
} return _persistentStoreCoordinator;
} - (NSManagedObjectContext *)managedObjectContext {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
if (_managedObjectContext != nil) {
return _managedObjectContext;
} NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (!coordinator) {
return nil;
}
_managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
return _managedObjectContext;
} #pragma mark - Core Data Saving support - (void)saveContext {
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
NSError *error = nil;
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// 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.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
} @end

假如你在.xcdatamodeld中生成了如下实体和实体属性:

那么在VC中获取数据库内容和添加数据库内容的代码如下:
   //从Core Data中获得已有数据
id appDelegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *managedContext = [appDelegate managedObjectContext];
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
@try {
self.people = [NSMutableArray arrayWithArray:[managedContext executeFetchRequest:fetchRequest error:nil]];
}
@catch (NSException *exception) {
NSLog(@"Could not fetch %@", [exception userInfo]);
}
@finally {
NSLog(@"Fetch Successful");
} //为数据库添加实体实例
id appDelegate = [UIApplication sharedApplication].delegate;
//NSManagedObjectContext可以看做内存中用来处理managedObjects的暂存器
NSManagedObjectContext *mangedContext = [appDelegate managedObjectContext];
//下面两种方法都可以获得Person实体
// NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:mangedContext];
// NSManagedObject *person = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:mangedContext];
// [person setValue:name forKey:@"name"];
NSManagedObject *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:mangedContext];
[person setValue:name forKey:@"name"];
@try {
[mangedContext save:nil];
[self.people addObject:person];
}
@catch (NSException *exception) {
NSLog(@"Could not save %@", [exception userInfo]);
}
@finally {
NSLog(@"Save Successfullt!");
}
 
 
 

最新文章

  1. Freemarker与Servlet
  2. 面试题目——《CC150》排序与查找
  3. HDU 4433 locker(SPFA+DP)
  4. CSS+HTML网页设计与布局(学习笔记1)
  5. 利用堆排序找出数组中前n大的元素
  6. 黑马程序员——JAVA基础之String和StringBuffer
  7. android下asynchttp库对于session的支持
  8. 剑指offer--13题
  9. 为网站添加网址图标favicon.ico
  10. iOS中的谓词(NSPredicate)使用
  11. 拒绝卡顿——在WPF中使用多线程更新UI
  12. Spring MVC之messageConverters
  13. [转] 消息系统该Push/Pull模式分析
  14. chromedriver 与 chrome关联关系
  15. linux自旋锁
  16. java reflection总结
  17. Office Web Apps 2013 修改Excel在线查看文件大小限制
  18. Fiddler实战深入研究(二)[转载]
  19. IOS git 删除仓库 新建仓库 提交 合并 操作 码云
  20. 手淘H5移动端适配方案flexible源码分析

热门文章

  1. 模态运行EXE程序
  2. 获取Delphi所有类的类信息
  3. weblogic启动报错之未修改hosts产生错误
  4. FFT(快速傅里叶变换):HDU 5307 He is Flying
  5. 【宽搜】Vijos P1360 八数码问题
  6. Combination Sum II —— LeetCode
  7. SRM 397(1-250pt)
  8. 网络编程之TCP异步群聊:客户端代码
  9. [置顶] C++中RTTI机制剖析
  10. JavaScript交换两个变量值的七种解决方案