標籤:des style blog http color io os 使用 ar
Core Data是ORM架構,很像.NET架構中的EntityFramework。使用的基本步驟是:
- 在項目屬性裡引入CoreData.framework (標準庫)
- 在項目中建立DataModel (產生*.xcdatamodeld檔案)
- 在DataModel裡建立Entity
- 為Entity產生標頭檔(菜單Editor/Create NSMangedObject Subclass...)
- 在項目唯一的委託類(AppDelegate.h, AppDelegate.m)裡添加managedObjectContext 用來操作Core Data
- 代碼任意位置引用 managedObjectContext 讀寫資料
模型:(注意:myChapter, myContent這些關係都是Cascade,這樣刪父物件時才會刪除子物件)
產生的標頭檔:
/* Book.h */@interface Book : NSManagedObject@property (nonatomic, retain) NSNumber * bookId;@property (nonatomic, retain) NSString * name;@property (nonatomic, retain) NSString * author;@property (nonatomic, retain) NSString * summary;@property (nonatomic, retain) NSSet *myChapters;@end@interface Book (CoreDataGeneratedAccessors)- (void)addMyChaptersObject:(NSManagedObject *)value;- (void)removeMyChaptersObject:(NSManagedObject *)value;- (void)addMyChapters:(NSSet *)values;- (void)removeMyChapters:(NSSet *)values;@end/* Chapter.h */@class Book;@interface Chapter : NSManagedObject@property (nonatomic, retain) NSNumber * chapId;@property (nonatomic, retain) NSString * name;@property (nonatomic, retain) NSNumber * orderId;@property (nonatomic, retain) Book *ownerBook;@property (nonatomic, retain) NSManagedObject *myContent;@end/* TextContent.h */@class Chapter;@interface TextContent : NSManagedObject@property (nonatomic, retain) NSNumber * chapId;@property (nonatomic, retain) NSString * text;@property (nonatomic, retain) Chapter *ownerChapter;@end
委託類代碼
AppDelegate.h
// AppDelegate.h#import <UIKit/UIKit.h>#import <CoreData/CoreData.h>#import "Book.h"#import "Chapter.h"#import "TextContent.h"@interface AppDelegate : UIResponder <UIApplicationDelegate>@property (strong, nonatomic) UIWindow *window;@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;@end
AppDelegate.m
@implementation AppDelegate@synthesize managedObjectContext = _managedObjectContext;-(NSManagedObjectContext *)managedObjectContext{ if (_managedObjectContext != nil) { return _managedObjectContext; } _managedObjectContext = [[NSManagedObjectContext alloc]init]; // 設定資料庫路徑 NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask]lastObject]; NSURL *storeDataBaseURL = [url URLByAppendingPathComponent:@"BOOKS.sqlite"]; // 建立presistentStoreCoordinator NSError *error = nil; NSPersistentStoreCoordinator *presistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[NSManagedObjectModel mergedModelFromBundles: nil]]; // 指定儲存類型和路徑 if (![presistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeDataBaseURL options:nil error:&error]) { NSLog(@"error : %@", error); } [_managedObjectContext setPersistentStoreCoordinator: presistentStoreCoordinator]; return _managedObjectContext;}
使用_managedObjectContext操作Core Data
// 儲存新對象-(void) testStore{ // 從AppDelegate 獲得context AppDelegate *appDelegate = [UIApplication sharedApplication].delegate; NSManagedObjectContext *context = [appDelegate managedObjectContext]; // 第一個章節 TextContent *content1 = [NSEntityDescription insertNewObjectForEntityForName:@"TextContent" inManagedObjectContext:context]; content1.chapId = [NSNumber numberWithInt:100]; content1.text = @"hello1"; Chapter *chapter1 = (Chapter *)[NSEntityDescription insertNewObjectForEntityForName:@"Chapter" inManagedObjectContext:context]; chapter1.name = @"hello1"; chapter1.orderId = [NSNumber numberWithInt:0]; chapter1.chapId = [NSNumber numberWithInt:100]; chapter1.myContent = content1; // 第二個章節 TextContent *content2 = [NSEntityDescription insertNewObjectForEntityForName:@"TextContent" inManagedObjectContext:context]; content2.chapId = [NSNumber numberWithInt:100]; content2.text = @"hello2"; Chapter *chapter2 = (Chapter *)[NSEntityDescription insertNewObjectForEntityForName:@"Chapter" inManagedObjectContext:context]; chapter2.name = @"hello2"; chapter2.orderId = [NSNumber numberWithInt:1]; chapter2.chapId = [NSNumber numberWithInt:101]; chapter2.myContent = content2; // 書籍對象 Book *book = (Book *)[NSEntityDescription insertNewObjectForEntityForName:@"Book" inManagedObjectContext:context]; book.bookId = [NSNumber numberWithInt:100]; book.name = @"hello"; book.author = @"Kitty"; book.summary = @"test"; [book addMyChaptersObject:chapter1]; [book addMyChaptersObject:chapter2]; // 提交到持久儲存 if ([context hasChanges]) { [context save:nil]; }}// 讀取對象-(void) testRead{ // 從AppDelegate 獲得context AppDelegate *appDelegate = [UIApplication sharedApplication].delegate; NSManagedObjectContext *context = [appDelegate managedObjectContext]; // 產生查詢對象 (查詢全部資料) NSEntityDescription *entityDescr = [NSEntityDescription entityForName:@"Book" inManagedObjectContext:context]; NSFetchRequest *request = [[NSFetchRequest alloc]init]; [request setEntity:entityDescr]; // 執行查詢 NSError *error; NSArray *arrayBooks = [context executeFetchRequest:request error:&error]; // 定義排序方式 (根據集合中Chapter對象的orderId屬性排序,升序) NSSortDescriptor *chaptersDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"orderId" ascending:YES]; // 遍曆結果集 for (Book *book in arrayBooks) { // 使用當前對象屬性 NSLog(@"book name = %@", book.name); // 使用當前對象的集合屬性,轉成數組 NSArray *arrayChapters = [book.myChapters allObjects]; // 排序 arrayChapters = [arrayChapters sortedArrayUsingDescriptors:[NSArray arrayWithObjects:chaptersDescriptor,nil]]; // 遍曆子數組 for (Chapter *chapter in arrayChapters) { NSLog(@"chapter name = %@", chapter.name); TextContent *content = (TextContent*) chapter.myContent; NSLog(@"chapter text = %@", content.text); } }}// 更新對象屬性-(void) testUpdate{ // 從AppDelegate 獲得context AppDelegate *appDelegate = [UIApplication sharedApplication].delegate; NSManagedObjectContext *context = [appDelegate managedObjectContext]; // 產生Request對象 NSEntityDescription *entityDescr = [NSEntityDescription entityForName:@"Book" inManagedObjectContext:context]; NSFetchRequest *request = [[NSFetchRequest alloc]init]; [request setEntity:entityDescr]; // 執行查詢 NSError *error; NSArray *array = [context executeFetchRequest:request error:&error]; // 更改對象屬性 Book * book = array[0]; book.name = @"BOOKS"; // 提交到持久儲存 if ([context hasChanges]) { [context save:nil]; }}// 刪除對象-(void) testRemove{ // 從AppDelegate 獲得context AppDelegate *appDelegate = [UIApplication sharedApplication].delegate; NSManagedObjectContext *context = [appDelegate managedObjectContext]; // 產生Request對象 NSEntityDescription *entityDescr = [NSEntityDescription entityForName:@"Book" inManagedObjectContext:context]; NSFetchRequest *request = [[NSFetchRequest alloc]init]; [request setEntity:entityDescr]; // 執行查詢 NSError *error; NSArray *array = [context executeFetchRequest:request error:&error]; // 遍曆刪除對象,因為在模型裡把關係設定為Cascade,所以子物件會被自動刪除 for (Book *book in array) { [context deleteObject:book]; } // 提交到持久儲存 if ([context hasChanges]) { [context save:nil]; }}
iOS: Core Data入門