日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

CoreData的增刪改查

 求知665 2015-08-03

近幾天一直在使用 CoreData, 以前覺得它是一門高深的技術(shù), 等自己用了之后才覺得,它是那么的平易近人.

一: 首先我們要在創(chuàng)建應(yīng)用程序的時候勾選 UseCoreData 選項, 當(dāng)然也可以自己后期創(chuàng)建.

系統(tǒng)會生成如下AppDelegate.h的文件

 1 #import <UIKit/UIKit.h>
 2 
 3 @interface AppDelegate : UIResponder <UIApplicationDelegate>
 4 
 5 @property (strong, nonatomic) UIWindow *window;
 6 
 7 // 上下文對象
 8 @property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
 9 // 數(shù)據(jù)模型
10 @property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
11 // 協(xié)調(diào)者
12 @property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
13 
14 // 在應(yīng)用程序終止的時候會調(diào)用該方法
15 - (void)saveContext;
16 // 得到應(yīng)用程序的 Documents 路徑, 將數(shù)據(jù)庫存在此目錄下
17 - (NSURL *)applicationDocumentsDirectory;
18 
19 @end

AppDelegate.m 文件會多出如下幾個方法:

 1 - (void)applicationWillTerminate:(UIApplication *)application
 2 {
 3     // 保存上下文對象的方法在此調(diào)用(程序結(jié)束的時候)
 4     [self saveContext];
 5 }
 6 
 7 #pragma makr - save context
 8 - (void)saveContext
 9 {
10     // 程序意外終止就會調(diào)用此方法
11     NSError *error = nil;
12     NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
13     if (managedObjectContext != nil) {
14         if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
15             NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
16             abort();
17         } 
18     }
19 }
20 
21 #pragma mark - Core Data stack
22 - (NSManagedObjectContext *)managedObjectContext
23 {
24     // 創(chuàng)建上下文對象
25     if (_managedObjectContext != nil) {
26         return _managedObjectContext;
27     }
28     
29     NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
30     if (coordinator != nil) {
31         _managedObjectContext = [[NSManagedObjectContext alloc] init];
32         [_managedObjectContext setPersistentStoreCoordinator:coordinator];
33     }
34     return _managedObjectContext;
35 }
36 
37 - (NSManagedObjectModel *)managedObjectModel
38 {
39     // 創(chuàng)建數(shù)據(jù)模型
40     if (_managedObjectModel != nil) {
41         return _managedObjectModel;
42     }
43     NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"CoreDataDemo02" withExtension:@"momd"];
44     _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
45     return _managedObjectModel;
46 }
47 - (NSPersistentStoreCoordinator *)persistentStoreCoordinator
48 {
49     // 創(chuàng)建協(xié)調(diào)者,也就是存儲區(qū)
50     if (_persistentStoreCoordinator != nil) {
51         return _persistentStoreCoordinator;
52     }
53     
54     NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreDataDemo02.sqlite"];
55     
56     NSError *error = nil;
57     _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
58     if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
59         NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
60         abort();
61     }    
62     
63     return _persistentStoreCoordinator;
64 }
65 
66 #pragma mark - Application's Documents directory
67 - (NSURL *)applicationDocumentsDirectory
68 {
69     // 得到 Documents 目錄
70     return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
71 }

這就是系統(tǒng)為我們搭建好的框架,我們只需要進(jìn)行數(shù)據(jù)操作便可.

二: 1)我們要在 CoreData 模板下添加實體以及實體的屬性,如圖:

2) 新建文件, 集資選擇 CoreData-->NSManagedObjectSubClass, 選擇為 Person 實體創(chuàng)建類便可.如下:

Person.h 文件

 1 #import <Foundation/Foundation.h>
 2 #import <CoreData/CoreData.h>
 3 
 4 
 5 @interface Person : NSManagedObject
 6 
 7 @property (nonatomic, retain) NSString * firstName;
 8 @property (nonatomic, retain) NSString * lastName;
 9 @property (nonatomic, retain) NSNumber * age;
10 
11 @end

Person.m 文件

 1 #import "Person.h"
 2 
 3 
 4 @implementation Person
 5 
 6 @dynamic firstName;
 7 @dynamic lastName;
 8 @dynamic age;
 9 
10 @end

現(xiàn)在我們的環(huán)境已經(jīng)準(zhǔn)備完畢:

三: 1) 寫入數(shù)據(jù)

 1 - (void)insertData
 2 {
 3     // 創(chuàng)建實體
 4     Person * newPerson = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.managedObjectContext];
 5     // 賦值
 6     if (newPerson != nil) {
 7         newPerson.firstName = @"Zero";
 8         newPerson.lastName = @"Hour";
 9         newPerson.age = [NSNumber numberWithInt:20];
10         
11         // 保存數(shù)據(jù)
12         NSError * savingError = nil;
13         if ([self.managedObjectContext save:&savingError]) {
14             NSLog(@"success");
15         }else {
16             NSLog(@"failed to save the context error = %@", savingError);
17         }
18     }else {
19         NSLog(@"failed to create the new person");
20     }
21 }

2) 刪除數(shù)據(jù)

 1 - (void)deleteData
 2 {
 3     NSFetchRequest * fetchRequest = [[NSFetchRequest alloc] init];
 4     NSEntityDescription * entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.managedObjectContext];
 5     [fetchRequest setEntity:entity];
 6     
 7     NSError * requestError = nil;
 8     NSArray * persons = [self.managedObjectContext executeFetchRequest:fetchRequest error:&requestError];
 9     
10     if ([persons count] > 0) {
11         
12         Person * lastPerson = [persons lastObject];
13         // 刪除數(shù)據(jù)
14         [self.managedObjectContext deleteObject:lastPerson];
15         if ([lastPerson isDeleted]) {
16             NSLog(@"successfully deleted the last person");
17             NSError * savingError = nil;
18             if ([self.managedObjectContext save:&savingError]) {
19                 NSLog(@"successfully saved the context");
20 
21             }else {
22                 NSLog(@"failed to save the context error = %@", savingError);
23             }
24         }else {
25         
26             NSLog(@"failed to delete the last person");
27         }
28     }else {
29         NSLog(@"could not find any person entity in the context");
30     }
31 }

3) 更改數(shù)據(jù)

 1 - (void)updateData
 2 {
 3     NSFetchRequest * fetchRequest = [[NSFetchRequest alloc] init];
 4     NSEntityDescription * entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.managedObjectContext];
 5     [fetchRequest setEntity:entity];
 6     
 7     NSError * requestError = nil;
 8     NSArray * persons = [self.managedObjectContext executeFetchRequest:fetchRequest error:&requestError];
 9     
10     if ([persons count] > 0) {
11         
12         Person * lastPerson = [persons lastObject];
13         // 更新數(shù)據(jù)
14         lastPerson.firstName = @"Hour";
15         lastPerson.lastName = @"Zero";
16         lastPerson.age = @21;
17 
18         NSError * savingError = nil;
19         if ([self.managedObjectContext save:&savingError]) {
20             NSLog(@"successfully saved the context");
21             
22         }else {
23             NSLog(@"failed to save the context error = %@", savingError);
24         }
25 
26 
27     }else {
28         NSLog(@"could not find any person entity in the context");
29     }
30 }

4) 查詢數(shù)據(jù)

 1 - (void)findData
 2 {
 3     NSFetchRequest * fetchRequest = [[NSFetchRequest alloc] init];
 4     NSEntityDescription * entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.managedObjectContext];
 5     [fetchRequest setEntity:entity];
 6     
 7     // 設(shè)置排序條件
 8     NSSortDescriptor * ageSort = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:YES];
 9     NSSortDescriptor * firstNameSort = [[NSSortDescriptor alloc] initWithKey:@"firstName" ascending:YES];
10     NSArray * sortDescriptors = @[ageSort, firstNameSort];
11     [fetchRequest setSortDescriptors:sortDescriptors];
12     
13     // 設(shè)置查詢條件
14     NSPredicate * agePre = [NSPredicate predicateWithFormat:@"age > 18"];
15     [fetchRequest setPredicate:agePre];
16     
17     NSError * requestError = nil;
18     NSArray * persons = [self.managedObjectContext executeFetchRequest:fetchRequest error:&requestError];
19     int counter = 0;
20     for (Person * thisPerson in persons) {
21         NSLog(@"person-->%d, firstName = %@, lastName = %@, age = %d", counter, thisPerson.firstName, thisPerson.lastName, [thisPerson.age intValue]);
22         counter ++;
23     }
24 }

好了自己目前只學(xué)習(xí)了這么多, CoreData 是非常好用的, 我會更加深入的去學(xué)習(xí)的,再見!

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多