core文件如何查看,關于CoreData的理解和使用.

 2023-12-06 阅读 22 评论 0

摘要:CoreData是蘋果官方推出的一種方便的面向對象的存儲方式,相信大家都已經對其有所了解,但是對于CoreData的概念大家都存在部分的誤區.給大家推薦個網址是蘋果的官方文檔的翻譯版(http://objccn.io/issue-4-1/)這里詳細的解釋了CoreData存在以及出現的意義.下面我就帶大家來學習

CoreData是蘋果官方推出的一種方便的面向對象的存儲方式,相信大家都已經對其有所了解,但是對于CoreData的概念大家都存在部分的誤區.給大家推薦個網址是蘋果的官方文檔的翻譯版(http://objccn.io/issue-4-1/)這里詳細的解釋了CoreData存在以及出現的意義.下面我就帶大家來學習下如何使用CoreData.

今天我們先學習最基礎的CoreData的操作(單表操作)

core文件如何查看、第一步 創建一個帶有CoreData的工程.

創建完成帶有CoreData的工程后我們可以看到我們工程左邊列表里有一個名字叫做CoreDataTest.xcdatamodeld的文件在哪里就是我們創建我們Model類實體文件的地方.

然后我們打開我們看到的那個文件,在里面我們創建一個叫做ClassEntity的實體名稱.

在我們創建完成那個實體文件以后我們看到我們的中間列表里面有一個添加實體屬性的位置.在這里我們添加三條屬性.名字分別為name sex age 類型全部選擇是string

在屬性添加完成后我們就可以去生成對應的實體類文件我們需要先選中CoreDataTest.xcdatamodeld這個文件然后選擇菜單欄上的Editor選擇Creat NSManagerObject Subclass...

創建完成后我們可以看到兩個叫做ClassEntity的文件被創建好了,然后我們再來看下其他不同于以往工程的地方.我們先來打開看下我們的AppDelegate.h文件,我們可以看到在AppDelegate.h文件中和以前我們創建的工程不同的地方.

#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>@interface AppDelegate : UIResponder <UIApplicationDelegate>@property (strong, nonatomic) UIWindow *window;//被管理者對象上下文
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;//數據模型器管理類
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;//數據連接器工具類 (連接助理)
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;//通過對上下文的保存,將上下文管理的對象保存到實體數據庫.
- (void)saveContext;//獲取數據庫所在的路徑
- (NSURL *)applicationDocumentsDirectory;@end

看完AppDelegate.h中的不同后我們來看下AppDelegate.m中有什么不同.

#pragma mark - Core Data stack@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;- (NSURL *)applicationDocumentsDirectory {// The directory the application uses to store the Core Data store file. This code uses a directory named "com.lanou.LessonCoreData" in the application's documents directory.NSLog(@"%@",[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]);return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}- (NSManagedObjectModel *)managedObjectModel {// The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.if (_managedObjectModel != nil) {return _managedObjectModel;}//momd 去查詢xcdatamodeldNSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"LessonCoreData" withExtension:@"momd"];//創建數據器模型工具類._managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];return _managedObjectModel;
}- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.if (_persistentStoreCoordinator != nil) {return _persistentStoreCoordinator;}// Create the coordinator and store//使用數據模型器工具類實例化數據連接器工具類._persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];//數據庫的絕對路徑.NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"LessonCoreData.sqlite"];NSError *error = nil;NSString *failureReason = @"There was an error creating or loading the application's saved data.";//創建數據庫的過程.//1.數據持久化類型//2.設置信息//3.數據庫的絕對路徑.//4.配置SQL數據的選項//5.錯誤信息的賦值.if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {// Report any error we got.NSMutableDictionary *dict = [NSMutableDictionary dictionary];dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";dict[NSLocalizedFailureReasonErrorKey] = failureReason;dict[NSUnderlyingErrorKey] = error;error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];// Replace this with code to handle the error appropriately.// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.NSLog(@"Unresolved error %@, %@", error, [error userInfo]);//程序中斷abort();}return _persistentStoreCoordinator;
}- (NSManagedObjectContext *)managedObjectContext {// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)if (_managedObjectContext != nil) {return _managedObjectContext;}//通過GET方法創建數據連接器工具類NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];//判斷數據器連接工具類是否為空if (!coordinator) {return nil;}//創建數據管理器工具類_managedObjectContext = [[NSManagedObjectContext alloc] init];//設置數據管理器工具類的數據連接器.[_managedObjectContext setPersistentStoreCoordinator:coordinator];return _managedObjectContext;
}#pragma mark - Core Data Saving support
//保存你當前的操作到數據庫中.
- (void)saveContext {NSManagedObjectContext *managedObjectContext = self.managedObjectContext;if (managedObjectContext != nil) {NSError *error = nil;if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {// Replace this implementation with code to handle the error appropriately.// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.NSLog(@"Unresolved error %@, %@", error, [error userInfo]);abort();}}
}

這些就是我們在創建完成一個帶有CoreData的工程和以前我們創建的工程的區別.然后我們來看下我們當前應該如何對我們當前創建的數據庫來操作.首先進入到我們當前需要用到CoreData的類文件中創建AppDelegate的實例,然后再當前類的- (void)viewWillDidLoad方法中去實現對CoreData的操作.

#import "ViewController.h"
#import "AppDelegate.h"
#import "ClassEntity.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {[super viewDidLoad];//獲取當前的AppDelegate的實例.AppDelegate *appdelegate = [UIApplication sharedApplication].delegate;為數據庫中增加數據//創建當前實體類的實體描述NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"ClassEntity" inManagedObjectContext:appdelegate.managedObjectContext];//通過實體描述文件來創建當前類的實例.ClassEntity *classEntity = [[ClassEntity alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:appdelegate.managedObjectContext];//為實例的屬性賦值.classEntity.name = @"張三";classEntity.sex = @"男";classEntity.age = @"21";//保存操作到真實的數據庫內.[appdelegate saveContext];查詢數據庫內存放的實體內容.//創建查詢語句NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"ClassEntity"];//通過AppDelegate來查詢你想要的數據庫.//注意返回值為數組.NSArray *arr = [appdelegate.managedObjectContext executeFetchRequest:request error:nil];//打印數組NSLog(@"%@",arr);刪除數據庫中存放的實體.//通過查詢獲取到你需要刪除的表單中的所有內容.//通過返回值獲取到的數組來查找你當前想要的實體位置.ClassEntity *classEntity1 = [arr objectAtIndex:0];//通過AppDelegate[appdelegate.managedObjectContext deleteObject:classEntity1];//通過AppDelegate來保存到你的真實數據庫中.[appdelegate saveContext];// Do any additional setup after loading the view, typically from a nib.
}

這些就是本次的CoreData是如何使用的.這次的內容也就到這里結束了.下次會和大家分享多表的CoreData的操作.最后附上我的文件列表截圖

.

?

轉載于:https://www.cnblogs.com/xiangnizhidao/p/4858496.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/3/192351.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息