(1)NSManagedObjectContext(被管理的數(shù)據(jù)上下文)
操作實(shí)際內(nèi)容(操作持久層)
作用:插入數(shù)據(jù),查詢數(shù)據(jù)耳奕,刪除數(shù)據(jù)
(2)NSManagedObjectModel(被管理的數(shù)據(jù)模型)
數(shù)據(jù)庫所有表格或數(shù)據(jù)結(jié)構(gòu),包含各實(shí)體的定義信息
作用:添加實(shí)體的屬性瞻佛,建立屬性之間的關(guān)系
操作方法:視圖編輯器梅忌,或代碼
(3)NSPersistentStoreCoordinator(持久化存儲助理)
相當(dāng)于數(shù)據(jù)庫的連接器
作用:設(shè)置數(shù)據(jù)存儲的名字,位置僧鲁,存儲方式虐呻,和存儲時(shí)機(jī)
(4)NSManagedObject(被管理的數(shù)據(jù)記錄)
相當(dāng)于數(shù)據(jù)庫中的表格記錄
(5)NSFetchRequest(獲取數(shù)據(jù)的請求)
相當(dāng)于查詢語句
(6)NSEntityDescription(實(shí)體結(jié)構(gòu))
相當(dāng)于表格結(jié)構(gòu)
(7)后綴為.xcdatamodeld的包
里面是.xcdatamodel文件,用數(shù)據(jù)模型編輯器編輯
編譯后為.momd或.mom文件
1.自定義封裝的 CoreData管理類HMTCoreDataManager
.h
#import
#import
/**
*? 數(shù)據(jù)存儲成功的代碼塊
*/
typedef void(^HandleSaveSuccessedBlock)();
/**
*? 數(shù)據(jù)存儲失敗的代碼塊
*/
typedef void(^HandleSaveFailedBlock)(NSError *);
@interface HMTCoreDataManager : NSObject
@property (nonatomic,strong)NSManagedObjectContext *managedObjectContext;? //? 托管對象上下文
/**
*? 創(chuàng)建一個(gè)單例對象
*
*? @return 單例對象
*/
+ (HMTCoreDataManager *)defaultManager;
/**
*? 根據(jù)實(shí)體描述獲得托管對象
*
*? @param entityName? 指定實(shí)體描述名字
*? @param aClass? ? ? 要獲取的托管對象
*
*? @return? 托管對象實(shí)例
*/
- (NSManagedObject *)managedObjectWithEntityName:(NSString *)entityName managedObjectClass:(Class)aClass;
/**
*? 數(shù)據(jù)存儲到磁盤中成功和失敗響應(yīng)的方法,參數(shù)為2個(gè)block
*
*? @param aSuccessedHandler
*? @param aFailedHandler
*/
- (void)saveWithSuccessedHandler:(HandleSaveSuccessedBlock)aSuccessedHandler failedHandler:(HandleSaveFailedBlock)aFailedHandler;
//? 插入數(shù)據(jù)
- (void)insertCoreData;
//? 查詢
- (NSMutableArray*)selectData:(NSString *)name;
//? 刪除
- (void)deleteData:(NSManagedObject *)object;
//? 更新
- (void)updateData:(NSString* )newName;
@end
.m
#import "HMTCoreDataManager.h"
@interface HMTCoreDataManager ()
@property (nonatomic,strong) NSPersistentStoreCoordinator *persistentStoreCoordinator;? //? 持久化存儲協(xié)調(diào)器
@property (nonatomic,strong) NSManagedObjectModel * managedObjectModel;? //? 托管對象模型
@end
@implementation HMTCoreDataManager
static HMTCoreDataManager *manager = nil;
+ (HMTCoreDataManager *)defaultManager{
@synchronized(self){
if (manager == nil) {
manager = [[HMTCoreDataManager alloc] init];
}
}
/*
//? 通過GCD創(chuàng)建
static dispatch_once_t onceToken;
dispatch_once(&onceToken,^{
manager = [[HMTCoreDataManager alloc] init];
});
*/
return manager;
}
#pragma mark - 屬性的方便之處能在get方法中初始化
/**
*? 很多人對于這個(gè)上下文不太理解,開始我也不太理解,查了很多資料,感覺下面這個(gè)解釋比較通俗易懂
*? 托管對象上下文:
*? 托管對象上下文包含所有的托管對象寞秃,這些托管對象已經(jīng)為提交給數(shù)據(jù)庫準(zhǔn)備就緒斟叼,在托管對象上下文中,可以添加春寿、修改和刪除托管對象朗涩,
*? 這一層相當(dāng)于應(yīng)用程序和數(shù)據(jù)庫之間的緩沖區(qū)。
*/
- (NSManagedObjectContext *)managedObjectContext{
if (_managedObjectContext) {
return _managedObjectContext;
}
_managedObjectContext = [[NSManagedObjectContext alloc] init];
//? 為托管對象上下文指定一個(gè)持久化存儲協(xié)調(diào)器
[_managedObjectContext setPersistentStoreCoordinator:self.persistentStoreCoordinator];
return _managedObjectContext;
}
/**
*? 持久化存儲協(xié)調(diào)器(持久化存儲助理)
*? 持久化存儲協(xié)調(diào)器處理到數(shù)據(jù)存儲的連接绑改,并且包含一些底層信息谢床,像用到數(shù)據(jù)存儲的名字和位置
*? 一般我們無需與它直接打交道,上下文已經(jīng)封裝了對它的調(diào)用
*/
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator{
if (_persistentStoreCoordinator) {
return _persistentStoreCoordinator;
}
//? 初始化一個(gè)持久化存儲協(xié)調(diào)器必須依賴NSManagedObjectModel
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.managedObjectModel];
//? 存儲路徑(返回的是NSURL類型)為Documents目錄下厘线,以及數(shù)據(jù)庫名稱
NSURL *documentURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
NSURL *fileURL = [documentURL URLByAppendingPathComponent:@"myClass.sqlite"];
NSError *error = nil;
//? 加載持久化存儲數(shù)據(jù)(指定持久化存儲的數(shù)據(jù)類型识腿,默認(rèn)的是NSSQLiteStoreType,即SQLite數(shù)據(jù)庫)
[_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:fileURL options:nil error:&error];
if (error != nil) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"添加持久化存儲失敗" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil, nil];
[alert show];
}
return _persistentStoreCoordinator;
}
/**
*? 托管對象模型
*? 數(shù)據(jù)庫所有表格或數(shù)據(jù)結(jié)構(gòu)包含各實(shí)體的定義信息
*? 添加實(shí)體的屬性造壮,建立屬性之間的關(guān)系
*/
- (NSManagedObjectModel *)managedObjectModel{
if (_managedObjectModel) {
return _managedObjectModel;
}
//? 獲取托管對象模型文件的地址
//? 編譯器會自動將"xcdatamodeld"格式轉(zhuǎn)化為"momd"
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"myClassModel" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
- (NSManagedObject *)managedObjectWithEntityName:(NSString *)entityName managedObjectClass:(Class)aClass{
//? 創(chuàng)建"HMTClass"的實(shí)體描述
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"HMTClassEntity" inManagedObjectContext:self.managedObjectContext];
//? 通過"HMTClass"的實(shí)體描述創(chuàng)建HMTClass的托管對象
NSManagedObject *managedObject = [[aClass alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:self.managedObjectContext];
return managedObject;
}
- (void)saveWithSuccessedHandler:(HandleSaveSuccessedBlock)aSuccessedHandler failedHandler:(HandleSaveFailedBlock)aFailedHandler{
NSError *error = nil;
[self.managedObjectContext save:&error];
if (error != nil) {
aFailedHandler(error);
}else {
aSuccessedHandler();
}
}
@end
2. 創(chuàng)建模型文件ManagedObject的過程
3.將創(chuàng)建的模型文件轉(zhuǎn)化為對應(yīng)的類文件
第一種:command+n
第二種: 選中myClassModel.xcdatamodeld
之后都是一樣的--->選中模型文件--->選中要創(chuàng)建的實(shí)體
最后,就會生成前面圖片中的3個(gè)類,都是繼承了 NSManagedObject
------------------class-------------------------------
@class HMTStudent, HMTTeacher;
@interface HMTClass : NSManagedObject
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSSet *students;
@property (nonatomic, retain) HMTTeacher *teacher;
@end
@interface HMTClass (CoreDataGeneratedAccessors)
- (void)addStudentsObject:(HMTStudent *)value;
- (void)removeStudentsObject:(HMTStudent *)value;
- (void)addStudents:(NSSet *)values;
- (void)removeStudents:(NSSet *)values;
@end
#import "HMTClass.h"
#import "HMTStudent.h"
#import "HMTTeacher.h"
@implementation HMTClass
@dynamic name;
@dynamic students;
@dynamic teacher;
@end
------------------teacher-------------------------------
@class HMTClass;
@interface HMTTeacher : NSManagedObject
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSString * course;
@property (nonatomic, retain) HMTClass *myClass;
@end
#import "HMTTeacher.h"
#import "HMTClass.h"
@implementation HMTTeacher
@dynamic name;
@dynamic course;
@dynamic myClass;
@end
------------------student-------------------------------
@class HMTClass, HMTTeacher;
@interface HMTStudent : NSManagedObject
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSNumber * age;
@property (nonatomic, retain) HMTTeacher *teacher;
@property (nonatomic, retain) HMTClass *myClass;
@end
#import "HMTStudent.h"
#import "HMTClass.h"
#import "HMTTeacher.h"
@implementation HMTStudent
@dynamic name;
@dynamic age;
@dynamic teacher;
@dynamic myClass;
@end
4.準(zhǔn)備工作都OK了,最后進(jìn)行數(shù)據(jù)的持久化存儲
#pragma mark - 增刪改查
//? 插入數(shù)據(jù)操作(類似于FMDB做法,方法后面可帶你想存儲的數(shù)據(jù)對象,這里只是單純的演示)
//? - (void)insertCoreData:(AppleClass *)appleClass
- (void)insertCoreData{
//? 創(chuàng)建"HMTClass"的實(shí)體描述,傳入的正是前面標(biāo)注的實(shí)體描述名
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"HMTClassEntity" inManagedObjectContext:self.managedObjectContext];
//? 通過"HMTClass"的實(shí)體描述創(chuàng)建HMTClass的托管對象
HMTClass *hmtClass = [[HMTClass alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:self.managedObjectContext];
//? hmtClass.name = appleClass.name;
hmtClass.name = @"Apple";
//? 托管對象上下文將托管對象的更改保存到磁盤文件中
//? - save? 將數(shù)據(jù)保存到數(shù)據(jù)庫
NSError *error = nil;
[self.managedObjectContext save:&error];
if (error != nil) {
NSLog(@"添加失敗:%@",[error localizedDescription]);
}
}
//? 刪除數(shù)據(jù)操作
- (void)deleteData:(NSManagedObject *)object{
[self.managedObjectContext deleteObject:object];
NSError *error = nil;
[[HMTCoreDataManager defaultManager].managedObjectContext save:&error];
if (error != nil) {
NSLog(@"刪除失敗:%@",[error localizedDescription]);
}
}
//? 查詢數(shù)據(jù)操作(依據(jù)特定條件查詢,如果是select * 就直接不寫謂詞判斷語句)
- (NSMutableArray*)selectData:(NSString *)name{
//? 創(chuàng)建指定Entity的查詢語句
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"HMTClassEntity"];
//? 謂詞,原理和用法都類似于SQL中的where渡讼,作用相當(dāng)于數(shù)據(jù)庫的過濾取(我blog中OC分類有具體講到)
NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"name == \'%@\'",name],nil];
fetchRequest.predicate = predicate;
//? 查詢的結(jié)果按哪個(gè)key進(jìn)行排序,YES為升序
// NSSortDescriptor *timestampSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"classNO" ascending:YES];
// fetchRequest.sortDescriptors = @[timestampSortDescriptor];
//? 注意查詢返回的只能是NSArray類型
NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil];
NSMutableArray *resultArray = [NSMutableArray arrayWithArray:fetchedObjects];
return resultArray;
}
//? 更新數(shù)據(jù)操作
- (void)updateData:(NSString *)newName{
//? 創(chuàng)建指定Entity的查詢語句
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"HMTClassEntity"];
//? 注意查詢返回的只能是NSArray類型
NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil];
//? 更新
for (HMTClass *info in fetchedObjects) {
info.name = newName;
}
//保存
if ([self.managedObjectContext save:nil]) {
//更新成功
NSLog(@"更新成功");
}
}
@轉(zhuǎn)載請注明:http://blog.csdn.net/hmt20130412 ?謝謝!
@不錯的CoreData資料:
http://blog.csdn.net/rhljiayou/article/details/18037729
http://blog.csdn.net/kesalin/article/details/6739319
http://www.cnblogs.com/mybkn/articles/2472881.html