CoreData的使用(IOS学习)

——杂言:最近开始学习IOS7的开发,下文是在已经建好的项目里加入CoreData的结构,并实现一个基于coredata的简单save,query。

 

1. 引入Core Data Framework。选中项目-->Genaral-->Linked Frameworks and Libraries中添加“CoreData.Framework”。然后在prefix.pch中加入“#import<CoreData/CoreData.h>”

2. 加入数据模型,创建Model.xcdatamodeld文件。File-->New-->File-->IOS-->Core Data-->Data Model

3. 在Delegate中建立CoreData与Delegate的关联。点击XYZAppDelegate.h,在@interface与@end之中加入以下代码

1 @property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
2 @property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
3 @property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
4 
5 - (void) saveContext;
6 - (NSURL *) applicationDocumentsDirectory;

4. 之后在XYZAppDelegate.m的@implementation下面写入以下代码(注:标红的2处名字请与.xcdatamodeld文件名保持一致)

1 @synthesize managedObjectContext = _managedObjectContext;
2 @synthesize managedObjectModel = _managedObjectModel;
3 @synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
 1 - (void) saveContext
 2 {
 3     NSError *error = nil;
 4     
 5     NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
 6     if(managedObjectContext != nil){
 7         if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
 8             NSLog(@"Unresolved error%@, %@", error, [error userInfo]);
 9         }
10     }
11 }
12 - (NSManagedObjectContext *) managedObjectContext
13 {
14     if (_managedObjectContext != nil) {
15         return _managedObjectContext;
16     }
17     NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
18     if(coordinator != nil){
19         NSLog(@"coordinator is not null-----");
20         _managedObjectContext = [[NSManagedObjectContext alloc]init];
21         [_managedObjectContext setPersistentStoreCoordinator:coordinator];
22     }else{
23         NSLog(@"coordinator is null-----");
24     }
25     return _managedObjectContext;
26 }
27 - (NSManagedObjectModel *) managedObjectModel
28 {
29     if(_managedObjectModel != nil){
30         return _managedObjectModel;
31     }
32     NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Ratings" withExtension:@"momd"];
33     _managedObjectModel = [[NSManagedObjectModel alloc]initWithContentsOfURL:modelURL];
34     return _managedObjectModel;
35 }
36 - (NSPersistentStoreCoordinator *) persistentStoreCoordinator
37 {
38     if(_persistentStoreCoordinator != nil){
39         return _persistentStoreCoordinator;
40     }
41     NSURL *storeUrl = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Ratings.sqlite"];
42     NSError *error = nil;
43     NSLog(@"storeUrl: %@",[self applicationDocumentsDirectory]);
44     _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:[self managedObjectModel]];
45     if(![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]){
46         NSLog(@"Unresolved error %@%@", error, [error userInfo]);
47         abort();
48     }
49     return _persistentStoreCoordinator;
50 }
51 - (NSURL *) applicationDocumentsDirectory
52 {
53     return [[[NSFileManager defaultManager]URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask]lastObject];
54 }

 

5. 至此,Core Data的准备工作已经完毕。

6. 现在可以创建Entity并结合使用,打开Ratings.xcdatamodeld文件,面板如下(2种模式),可以点击并添加Entity(可以结合右侧属性面板使用)

7. 为entity添加.m和.h文件,File-->New->File->IOS->Core Data->NSManagedObject subclass

8. entity已经创建完成,可以开始在Controller中使用相关context操作。我的是XYZPlayersViewController。

9. XYZPlayersViewController.h中添加以下代码

1 @property (nonatomic, strong) NSManagedObjectContext *context;

10. XYZPlayersViewController.m中需要使用的地方添加以下代码

1 @synthesize context;
 1 XYZAppDelegate *delegate = (XYZAppDelegate *)[[UIApplication sharedApplication]delegate];
 2 self.context = delegate.managedObjectContext;
 3 
 4 Player *player = [NSEntityDescription insertNewObjectForEntityForName:@"Player"
 5                                                inManagedObjectContext:context];
 6 player.name = @"timelyxyz";
 7 player.game = @"Chess";
 8 player.rating = [NSNumber numberWithInt:100];
 9 
10 NSError *error = nil;
11 if(![context save:&error]){
12     NSLog(@"%@", [error localizedDescription]);
13 }
14 
15 NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
16 NSEntityDescription *entity = [NSEntityDescription entityForName:@"Player"
17                                           inManagedObjectContext:context];
18 [fetchRequest setEntity:entity];
19 
20 NSArray *fetchObjects = [context executeFetchRequest:fetchRequest error:&error];
21 for(NSManagedObject *info in fetchObjects){
22     NSLog(@"name: %@",[info valueForKey:@"name"]);
23     NSLog(@"game: %@", [info valueForKey:@"game"]);
24     NSLog(@"rating: %@", [info valueForKey:@"rating"]);
25 }

11. log输出如下

 

demo下载:Ratings

posted on 2014-03-04 16:41  timelyxyz  阅读(414)  评论(0编辑  收藏  举报

导航