初始化
- (NSManagedObjectContext *)context {
if (_context == nil) {
// 創(chuàng)建上下文對象,并發(fā)隊列設(shè)置為主隊列
_context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
// 創(chuàng)建托管對象模型,并使用Student.momd路徑當(dāng)做初始化參數(shù)
// .xcdatamodeld文件 編譯之后變成.momd文件 (.mom文件)
NSURL *modelPath = [[NSBundle mainBundle] URLForResource:@"Test" withExtension:@"momd"];
NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelPath];
// 創(chuàng)建持久化存儲調(diào)度器
NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
// 創(chuàng)建并關(guān)聯(lián)SQLite數(shù)據(jù)庫文件怯伊,如果已經(jīng)存在則不會重復(fù)創(chuàng)建
NSString *dataPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
dataPath = [dataPath stringByAppendingFormat:@"/%@.sqlite",@"CPStudent"];
// 創(chuàng)建
[coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:dataPath] options:options error:nil];
// 上下文對象設(shè)置屬性為持久化存儲器
_context.persistentStoreCoordinator = coordinator;
}
return _context;
}
- (NSPersistentContainer *)persistentContainer {
// 如果已經(jīng)存在持久容器,直接返回
if (_persistentContainer != nil) {
return _persistentContainer;
}
// 創(chuàng)建持久容器,通常與你的數(shù)據(jù)模型同名
_persistentContainer = [[NSPersistentContainer alloc] initWithName:@"test"];
// 完成持久容器的加載
[_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
if (error != nil) {
NSLog(@"Unresolved error %@, %@", error, error.userInfo);
abort(); // 處理初始化錯誤
}
}];
return _persistentContainer;
}
- (void)initCoreData {
NSPersistentContainer *container = [self persistentContainer];
[container loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
if (error) {
NSLog(@"Error loading Core Data store: %@, %@", error, error.userInfo);
abort(); // 處理初始化錯誤
}
NSManagedObjectContext *context = [self persistentContainer].viewContext;
NSManagedObject *newStudent = [NSEntityDescription insertNewObjectForEntityForName:@"newStudent" inManagedObjectContext:context];
[newStudent setValue:@"liming" forKey:@"name"];
[newStudent setValue:@(11) forKey:@"age"];
[newStudent setValue:@(100001) forKey:@"numebr"];
NSError *addError;
if (![context save:&addError]) {
NSLog(@"Error saving context: %@", addError.localizedDescription);
}
}];
}
增
- (CPStudent *)insertStudentData {
NSError *error = nil;
// 開始創(chuàng)建托管對象,并指明好創(chuàng)建的托管對象所屬實體名
CPStudent * student = [NSEntityDescription insertNewObjectForEntityForName:@"CPStudent" inManagedObjectContext:self.context];
//2.根據(jù)表Student中的鍵值夫啊,給NSManagedObject對象賦值
student.name = [NSString stringWithFormat:@"Mr-%d",arc4random() % 100];
student.age = arc4random() % 20;
student.sex = arc4random() % 2 == 0 ? @"男" : @"女" ;
student.height = arc4random() % 180;
student.number = arc4random() % 100;
student.father = @"aaa";
student.studentNumber = arc4random() % 100;
if ([self.context hasChanges] && ![self.context save:&error]) {
NSLog(@"Unresolved error %@, %@", error, error.userInfo);
abort();
return nil;
} else {
NSLog(@"插入數(shù)據(jù)成功");
}
return student;
}
刪
- (void)delete:(NSArray *)delStudents {
// 獲取數(shù)據(jù)的請求對象,指明對實體進行刪除操作
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"CPStudent"];
[delStudents enumerateObjectsUsingBlock:^(CPStudent *obj, NSUInteger idx, BOOL *stop) {
// 通過創(chuàng)建謂詞對象辆憔,然后過濾掉符合要求的對象撇眯,也就是要刪除的對象
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"number = %d",obj.number];
request.predicate = predicate;
// 通過執(zhí)行獲取操作,找到要刪除的對象即可
NSError *error = nil;
NSArray<CPStudent *> *students = [self.context executeFetchRequest:request error:&error];
// 開始真正操作虱咧,一一遍歷叛本,遍歷符合刪除要求的對象數(shù)組,執(zhí)行刪除操作
[students enumerateObjectsUsingBlock:^(CPStudent *obj, NSUInteger idx, BOOL *stop) {
[self.context deleteObject:obj];
}];
// 錯誤處理
if (error) {
NSLog(@"刪除失敗");
} else {
NSLog(@"刪除成功");
}
}];
// 最后保存數(shù)據(jù)彤钟,保存上下文。
if (self.context.hasChanges) {
[self.context save:nil];
}
}
改
- (void)modify:(NSArray *)modifyStudents {
// 獲取數(shù)據(jù)的請求對象跷叉,指明對實體進行刪除操作
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"CPStudent"];
[modifyStudents enumerateObjectsUsingBlock:^(CPStudent *obj, NSUInteger idx, BOOL *stop) {
// 通過創(chuàng)建謂詞對象逸雹,然后過濾掉符合要求的對象,也就是要刪除的對象
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"number = %d",obj.number];
request.predicate = predicate;
// 通過執(zhí)行獲取操作云挟,找到要刪除的對象即可
NSError *error = nil;
NSArray<CPStudent *> *students = [self.context executeFetchRequest:request error:&error];
// 開始真正操作梆砸,一一遍歷,遍歷符合刪除要求的對象數(shù)組园欣,執(zhí)行刪除操作
[students enumerateObjectsUsingBlock:^(CPStudent *obj, NSUInteger idx, BOOL *stop) {
obj.age += 1;
obj.sex = [obj.sex isEqualToString:@"男"] ? @"女" : @"男";
}];
// 錯誤處理
if (error) {
NSLog(@"改失敗");
} else {
NSLog(@"改成功");
}
}];
// 最后保存數(shù)據(jù)帖世,保存上下文。
if (self.context.hasChanges) {
[self.context save:nil];
}
}
查
- (NSArray<CPStudent *> *)fetchTapStudentData {
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"CPStudent"];
// 執(zhí)行獲取操作沸枯,獲取所有Student托管對象
NSError *error = nil;
NSArray<CPStudent *> *students = [self.context executeFetchRequest:request error:&error];
if (error) {
NSLog(@"失敗");
} else {
NSLog(@"查找數(shù)據(jù)成功");
}
return students;
}
數(shù)據(jù)遷移
輕數(shù)據(jù)遷移
適用場景:
- 添加日矫、刪除一個表或者屬性
- 屬性值可空與不可空的改變
- 重命名表或者屬性
- 單一的一次遷移(如果出現(xiàn)多次版本遷移要一起做赂弓,就要進行逐步遷移,不能用輕數(shù)據(jù)遷移)
//請求自動輕量級遷移
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
nil];
NSError *error = nil;
[coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:newDataPath] options:options error:nil];
自定義數(shù)據(jù)遷移
創(chuàng)建MappingModel在指定映射哪轿。使用NSEntityMigrationPolicy類來指定遷移策略盈魁。
- 使用NSPersistentStoreCoordinator持久化調(diào)度器來獲取當(dāng)前版本model
- 使用NSManagedObjectModel獲取最新model
- 對本版本,漸進式遷移窃诉。