Core Data資料持久化是對SQLite的一個更新,它是ios內建的,在說Core Data之前,我們先說說在CoreData中使用的幾個類。
(1) NSManagedObjectModel(被管理的對象模型)
相當于實體,不過它包含了實體間的關系
(2) NSManagedObjectContext(被管理的對象上下文)
操作實際内容
作用:插入資料 查詢 更新 删除
(3) NSPersistentStoreCoordinator(持久化存儲助理)
相當于資料庫的連接配接器
(4) NSFetchRequest(擷取資料的請求)
相當于查詢語句
(5)NSPredicate(相當于查詢條件)
(6)NSEntityDescription(實體結構)
(7)字尾名為.xcdatamodel的包
裡面的.xcdatamodel檔案,用資料模型編輯器編輯,編譯後為.momd或.mom檔案,這就是為什麼檔案中沒有這個東西,而我們的程式中用到這個東西而不會報錯的原因。
首先我們要建立模型對象

其次我們要生成模型對象的實體User,它是繼承NSManagedObjectModel的
點選之後你會發現它會自動的生成User,現在主要說一下,生成的User對象是這種形式的
這裡解釋一下dynamic 平常我們接觸的是synthesize
dynamic和synthesize有什麼差別呢?它的setter和getter方法不能自已定義
打開CoreData的SQL語句輸出開關
1.打開Product,點選EditScheme...
2.點選Arguments,在ArgumentsPassed On Launch中添加2項
1> -com.apple.CoreData.SQLDebug
2> 1
1 #import <UIKit/UIKit.h>
2 #import <CoreData/CoreData.h>
3 @class ViewController;
4
5 @interface AppDelegate : UIResponder <UIApplicationDelegate>
6
7 @property (strong, nonatomic) UIWindow *window;
8
9 @property (strong, nonatomic) ViewController *viewController;
10
11 @property(strong,nonatomic,readonly)NSManagedObjectModel* managedObjectModel;
12
13 @property(strong,nonatomic,readonly)NSManagedObjectContext* managedObjectContext;
14
15 @property(strong,nonatomic,readonly)NSPersistentStoreCoordinator* persistentStoreCoordinator;
16 @end
17
18
19 #import "AppDelegate.h"
20
21 #import "ViewController.h"
22
23 @implementation AppDelegate
24 @synthesize managedObjectModel=_managedObjectModel;
25 @synthesize managedObjectContext=_managedObjectContext;
26 @synthesize persistentStoreCoordinator=_persistentStoreCoordinator;
27 - (void)dealloc
28 {
29 [_window release];
30 [_viewController release];
31 [_managedObjectContext release];
32 [_managedObjectModel release];
33 [_persistentStoreCoordinator release];
34 [super dealloc];
35 }
36
37 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
38 {
39 self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
40 // Override point for customization after application launch.
41 self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];
42 self.window.rootViewController = self.viewController;
43 [self.window makeKeyAndVisible];
44 return YES;
45 }
46
47 - (void)applicationWillResignActive:(UIApplication *)application
48 {
49 // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
50 // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
51 }
52
53 - (void)applicationDidEnterBackground:(UIApplication *)application
54 {
55 // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
56 // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
57 }
58
59 - (void)applicationWillEnterForeground:(UIApplication *)application
60 {
61 // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
62 }
63
64 - (void)applicationDidBecomeActive:(UIApplication *)application
65 {
66 // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
67 }
68
69 - (void)applicationWillTerminate:(UIApplication *)application
70 {
71 // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
72 }
1 //托管對象
2 -(NSManagedObjectModel *)managedObjectModel
3 {
4 if (_managedObjectModel!=nil) {
5 return _managedObjectModel;
6 }
7 // NSURL* modelURL=[[NSBundle mainBundle] URLForResource:@"CoreDataExample" withExtension:@"momd"];
8 // _managedObjectModel=[[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
9 _managedObjectModel=[[NSManagedObjectModel mergedModelFromBundles:nil] retain];
10 return _managedObjectModel;
11 }
12 //托管對象上下文
13 -(NSManagedObjectContext *)managedObjectContext
14 {
15 if (_managedObjectContext!=nil) {
16 return _managedObjectContext;
17 }
18
19 NSPersistentStoreCoordinator* coordinator=[self persistentStoreCoordinator];
20 if (coordinator!=nil) {
21 _managedObjectContext=[[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
22
23 [_managedObjectContext setPersistentStoreCoordinator:coordinator];
24 }
25 return _managedObjectContext;
26 }
27 //持久化存儲協調器
28 -(NSPersistentStoreCoordinator *)persistentStoreCoordinator
29 {
30 if (_persistentStoreCoordinator!=nil) {
31 return _persistentStoreCoordinator;
32 }
33 // NSURL* storeURL=[[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreaDataExample.CDBStore"];
34 // NSFileManager* fileManager=[NSFileManager defaultManager];
35 // if(![fileManager fileExistsAtPath:[storeURL path]])
36 // {
37 // NSURL* defaultStoreURL=[[NSBundle mainBundle] URLForResource:@"CoreDataExample" withExtension:@"CDBStore"];
38 // if (defaultStoreURL) {
39 // [fileManager copyItemAtURL:defaultStoreURL toURL:storeURL error:NULL];
40 // }
41 // }
42 NSString* docs=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
43 NSURL* storeURL=[NSURL fileURLWithPath:[docs stringByAppendingPathComponent:@"CoreDataExample.sqlite"]];
44 NSLog(@"path is %@",storeURL);
45 NSError* error=nil;
46 _persistentStoreCoordinator=[[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
47 if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
48 NSLog(@"Error: %@,%@",error,[error userInfo]);
49 }
50 return _persistentStoreCoordinator;
51 }
52 //-(NSURL *)applicationDocumentsDirectory
53 //{
54 // return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
55 //}
56 @end
1 #import <UIKit/UIKit.h>
2 #import "AppDelegate.h"
3 @interface ViewController : UIViewController
4 @property (retain, nonatomic) IBOutlet UITextField *nameText;
5 @property (retain, nonatomic) IBOutlet UITextField *ageText;
6 @property (retain, nonatomic) IBOutlet UITextField *sexText;
7 @property(nonatomic,retain)AppDelegate* myAppDelegate;
8 - (IBAction)addIntoDataSource:(id)sender;
9 - (IBAction)query:(id)sender;
10 - (IBAction)update:(id)sender;
11 - (IBAction)del:(id)sender;
1 #import "ViewController.h"
2 #import "User.h"
3 @interface ViewController ()
4
5 @end
6
7 @implementation ViewController
8
9 - (void)viewDidLoad
10 {
11 [super viewDidLoad];
12 // Do any additional setup after loading the view, typically from a nib.
13 _myAppDelegate=(AppDelegate *)[[UIApplication sharedApplication] delegate];
14 }
15
16 - (void)didReceiveMemoryWarning
17 {
18 [super didReceiveMemoryWarning];
19 // Dispose of any resources that can be recreated.
20 }
21
22 - (void)dealloc {
23 [_nameText release];
24 [_ageText release];
25 [_sexText release];
26 [super dealloc];
27 }
28 //插入資料
29 - (IBAction)addIntoDataSource:(id)sender {
30 User* user=(User *)[NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:self.myAppDelegate.managedObjectContext];
31 [user setName:_nameText.text];
32 [user setAge:[NSNumber numberWithInteger:[_ageText.text integerValue]]];
33 [user setSex:_sexText.text];
34 NSError* error;
35 BOOL isSaveSuccess=[_myAppDelegate.managedObjectContext save:&error];
36 if (!isSaveSuccess) {
37 NSLog(@"Error:%@",error);
38 }else{
39 NSLog(@"Save successful!");
40 }
41
42 }
43 //查詢
44 - (IBAction)query:(id)sender {
45 NSFetchRequest* request=[[NSFetchRequest alloc] init];
46 NSEntityDescription* user=[NSEntityDescription entityForName:@"User" inManagedObjectContext:_myAppDelegate.managedObjectContext];
47 [request setEntity:user];
48 // NSSortDescriptor* sortDescriptor=[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
49 // NSArray* sortDescriptions=[[NSArray alloc] initWithObjects:sortDescriptor, nil];
50 // [request setSortDescriptors:sortDescriptions];
51 // [sortDescriptions release];
52 // [sortDescriptor release];
53 NSError* error=nil;
54 NSMutableArray* mutableFetchResult=[[_myAppDelegate.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
55 if (mutableFetchResult==nil) {
56 NSLog(@"Error:%@",error);
57 }
58 NSLog(@"The count of entry: %i",[mutableFetchResult count]);
59 for (User* user in mutableFetchResult) {
60 NSLog(@"name:%@----age:%@------sex:%@",user.name,user.age,user.sex);
61 }
62 [mutableFetchResult release];
63 [request release];
64 }
65 //更新
66 - (IBAction)update:(id)sender {
67 NSFetchRequest* request=[[NSFetchRequest alloc] init];
68 NSEntityDescription* user=[NSEntityDescription entityForName:@"User" inManagedObjectContext:_myAppDelegate.managedObjectContext];
69 [request setEntity:user];
70 //查詢條件
71 NSPredicate* predicate=[NSPredicate predicateWithFormat:@"name==%@",@"chen"];
72 [request setPredicate:predicate];
73 NSError* error=nil;
74 NSMutableArray* mutableFetchResult=[[_myAppDelegate.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
75 if (mutableFetchResult==nil) {
76 NSLog(@"Error:%@",error);
77 }
78 NSLog(@"The count of entry: %i",[mutableFetchResult count]);
79 //更新age後要進行儲存,否則沒更新
80 for (User* user in mutableFetchResult) {
81 [user setAge:[NSNumber numberWithInt:12]];
82
83 }
84 [_myAppDelegate.managedObjectContext save:&error];
85 [mutableFetchResult release];
86 [request release];
87
88 }
89 //删除
90 - (IBAction)del:(id)sender {
91 NSFetchRequest* request=[[NSFetchRequest alloc] init];
92 NSEntityDescription* user=[NSEntityDescription entityForName:@"User" inManagedObjectContext:_myAppDelegate.managedObjectContext];
93 [request setEntity:user];
94 NSPredicate* predicate=[NSPredicate predicateWithFormat:@"name==%@",@"chen"];
95 [request setPredicate:predicate];
96 NSError* error=nil;
97 NSMutableArray* mutableFetchResult=[[_myAppDelegate.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
98 if (mutableFetchResult==nil) {
99 NSLog(@"Error:%@",error);
100 }
101 NSLog(@"The count of entry: %i",[mutableFetchResult count]);
102 for (User* user in mutableFetchResult) {
103 [_myAppDelegate.managedObjectContext deleteObject:user];
104 }
105
106 if ([_myAppDelegate.managedObjectContext save:&error]) {
107 NSLog(@"Error:%@,%@",error,[error userInfo]);
108 }
109 }
110 @end