ios中的coredata的使用

article/2025/8/19 20:18:51

      Core Data数据持久化是对SQLite的一个升级,它是ios集成的,在说Core Data之前,我们先说说在CoreData中使用的几个类。

   (1)NSManagedObjectModel(被管理的对象模型)

           相当于实体,不过它包含 了实体间的关系

    (2)NSManagedObjectContext(被管理的对象上下文)

         操作实际内容

        作用:插入数据  查询  更新  删除

  (3)NSPersistentStoreCoordinator(持久化存储助理)

          相当于数据库的连接器

    (4)NSFetchRequest(获取数据的请求)    

        相当于查询语句

     (5)NSPredicate(相当于查询条件)

    (6)NSEntityDescription(实体结构)

    (7)后缀名为.xcdatamodel的包

        里面的.xcdatamodel文件,用数据模型编辑器编辑

       编译后为.momd或.mom文件,这就是为什么文件中没有这个东西,而我们的程序中用到这个东西而不会报错的原因

   首先我们要建立模型对象

   

  其次我们要生成模型对象的实体User,它是继承NSManagedObjectModel的

  

    点击之后你会发现它会自动的生成User,现在主要说一下,生成的User对象是这种形式的

 


这里解释一下dynamic  平常我们接触的是synthesize

 dynamic和synthesize有什么区别呢?它的setter和getter方法不能自已定义

打开CoreData的SQL语句输出开关

1.打开Product,点击EditScheme...
2.点击Arguments,在ArgumentsPassed On Launch中添加2项
1> -com.apple.CoreData.SQLDebug
2> 1

#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
@class ViewController;@interface AppDelegate : UIResponder <UIApplicationDelegate>@property (strong, nonatomic) UIWindow *window;@property (strong, nonatomic) ViewController *viewController;@property(strong,nonatomic,readonly)NSManagedObjectModel* managedObjectModel;@property(strong,nonatomic,readonly)NSManagedObjectContext* managedObjectContext;@property(strong,nonatomic,readonly)NSPersistentStoreCoordinator* persistentStoreCoordinator;
@end

#import "AppDelegate.h"#import "ViewController.h"@implementation AppDelegate
@synthesize managedObjectModel=_managedObjectModel;
@synthesize managedObjectContext=_managedObjectContext;
@synthesize persistentStoreCoordinator=_persistentStoreCoordinator;
- (void)dealloc
{[_window release];[_viewController release];[_managedObjectContext release];[_managedObjectModel release];[_persistentStoreCoordinator release];[super dealloc];
}- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];// Override point for customization after application launch.self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];self.window.rootViewController = self.viewController;[self.window makeKeyAndVisible];return YES;
}- (void)applicationWillResignActive:(UIApplication *)application
{// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}- (void)applicationDidEnterBackground:(UIApplication *)application
{// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}- (void)applicationWillEnterForeground:(UIApplication *)application
{// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}- (void)applicationDidBecomeActive:(UIApplication *)application
{// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}- (void)applicationWillTerminate:(UIApplication *)application
{// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
//托管对象
-(NSManagedObjectModel *)managedObjectModel
{if (_managedObjectModel!=nil) {return _managedObjectModel;}
//    NSURL* modelURL=[[NSBundle mainBundle] URLForResource:@"CoreDataExample" withExtension:@"momd"];
//    _managedObjectModel=[[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];_managedObjectModel=[[NSManagedObjectModel mergedModelFromBundles:nil] retain];return _managedObjectModel;
}
//托管对象上下文
-(NSManagedObjectContext *)managedObjectContext
{if (_managedObjectContext!=nil) {return _managedObjectContext;}NSPersistentStoreCoordinator* coordinator=[self persistentStoreCoordinator];if (coordinator!=nil) {_managedObjectContext=[[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];[_managedObjectContext setPersistentStoreCoordinator:coordinator];}return _managedObjectContext;
}
//持久化存储协调器
-(NSPersistentStoreCoordinator *)persistentStoreCoordinator
{if (_persistentStoreCoordinator!=nil) {return _persistentStoreCoordinator;}
//    NSURL* storeURL=[[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreaDataExample.CDBStore"];
//    NSFileManager* fileManager=[NSFileManager defaultManager];
//    if(![fileManager fileExistsAtPath:[storeURL path]])
//    {
//        NSURL* defaultStoreURL=[[NSBundle mainBundle] URLForResource:@"CoreDataExample" withExtension:@"CDBStore"];
//        if (defaultStoreURL) {
//            [fileManager copyItemAtURL:defaultStoreURL toURL:storeURL error:NULL];
//        }
//    }NSString* docs=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];NSURL* storeURL=[NSURL fileURLWithPath:[docs stringByAppendingPathComponent:@"CoreDataExample.sqlite"]];NSLog(@"path is %@",storeURL);NSError* error=nil;_persistentStoreCoordinator=[[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {NSLog(@"Error: %@,%@",error,[error userInfo]);}return _persistentStoreCoordinator;
}
//-(NSURL *)applicationDocumentsDirectory
//{
//    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
//}
@end

#import <UIKit/UIKit.h>
#import "AppDelegate.h"
@interface ViewController : UIViewController
@property (retain, nonatomic) IBOutlet UITextField *nameText;
@property (retain, nonatomic) IBOutlet UITextField *ageText;
@property (retain, nonatomic) IBOutlet UITextField *sexText;
@property(nonatomic,retain)AppDelegate* myAppDelegate;
- (IBAction)addIntoDataSource:(id)sender;
- (IBAction)query:(id)sender;
- (IBAction)update:(id)sender;
- (IBAction)del:(id)sender;

#import "ViewController.h"
#import "User.h"
@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad
{[super viewDidLoad];// Do any additional setup after loading the view, typically from a nib._myAppDelegate=(AppDelegate *)[[UIApplication sharedApplication] delegate];
}- (void)didReceiveMemoryWarning
{[super didReceiveMemoryWarning];// Dispose of any resources that can be recreated.
}- (void)dealloc {[_nameText release];[_ageText release];[_sexText release];[super dealloc];
}
//插入数据
- (IBAction)addIntoDataSource:(id)sender {User* user=(User *)[NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:self.myAppDelegate.managedObjectContext];[user setName:_nameText.text];[user setAge:[NSNumber numberWithInteger:[_ageText.text integerValue]]];[user setSex:_sexText.text];NSError* error;BOOL isSaveSuccess=[_myAppDelegate.managedObjectContext save:&error];if (!isSaveSuccess) {NSLog(@"Error:%@",error);}else{NSLog(@"Save successful!");}}
//查询
- (IBAction)query:(id)sender {NSFetchRequest* request=[[NSFetchRequest alloc] init];NSEntityDescription* user=[NSEntityDescription entityForName:@"User" inManagedObjectContext:_myAppDelegate.managedObjectContext];[request setEntity:user];
//    NSSortDescriptor* sortDescriptor=[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
//    NSArray* sortDescriptions=[[NSArray alloc] initWithObjects:sortDescriptor, nil];
//    [request setSortDescriptors:sortDescriptions];
//    [sortDescriptions release];
//    [sortDescriptor release];NSError* error=nil;NSMutableArray* mutableFetchResult=[[_myAppDelegate.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];if (mutableFetchResult==nil) {NSLog(@"Error:%@",error);}NSLog(@"The count of entry: %i",[mutableFetchResult count]);for (User* user in mutableFetchResult) {NSLog(@"name:%@----age:%@------sex:%@",user.name,user.age,user.sex);}[mutableFetchResult release];[request release];
}
//更新
- (IBAction)update:(id)sender {NSFetchRequest* request=[[NSFetchRequest alloc] init];NSEntityDescription* user=[NSEntityDescription entityForName:@"User" inManagedObjectContext:_myAppDelegate.managedObjectContext];[request setEntity:user];//查询条件NSPredicate* predicate=[NSPredicate predicateWithFormat:@"name==%@",@"chen"];[request setPredicate:predicate];NSError* error=nil;NSMutableArray* mutableFetchResult=[[_myAppDelegate.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];if (mutableFetchResult==nil) {NSLog(@"Error:%@",error);}NSLog(@"The count of entry: %i",[mutableFetchResult count]);//更新age后要进行保存,否则没更新for (User* user in mutableFetchResult) {[user setAge:[NSNumber numberWithInt:12]];}[_myAppDelegate.managedObjectContext save:&error];[mutableFetchResult release];[request release];}
//删除
- (IBAction)del:(id)sender {NSFetchRequest* request=[[NSFetchRequest alloc] init];NSEntityDescription* user=[NSEntityDescription entityForName:@"User" inManagedObjectContext:_myAppDelegate.managedObjectContext];[request setEntity:user];NSPredicate* predicate=[NSPredicate predicateWithFormat:@"name==%@",@"chen"];[request setPredicate:predicate];NSError* error=nil;NSMutableArray* mutableFetchResult=[[_myAppDelegate.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];if (mutableFetchResult==nil) {NSLog(@"Error:%@",error);}NSLog(@"The count of entry: %i",[mutableFetchResult count]);for (User* user in mutableFetchResult) {[_myAppDelegate.managedObjectContext deleteObject:user];}if ([_myAppDelegate.managedObjectContext save:&error]) {NSLog(@"Error:%@,%@",error,[error userInfo]);}
}
@end

对于多线程它是不安全的,需要进行特殊处理下次再说吧


http://chatgpt.dhexx.cn/article/Pkpv86jr.shtml

相关文章

CoreData使用

一、CoreData的简单使用 1.什么是CoreData 先认识一下这几个类 (1)NSManagedObjectContext&#xff08;被管理的数据上下文&#xff09; 作用&#xff1a;用来管理所有表的操作&#xff0c;对表的实体对应的数据库中的表的操作&#xff08;插入&#xff0c;查询&#xff0c;修改…

iOS CoreData的使用

CoreData是一个专门管理数据服务的框架&#xff0c;把OC对象和存储在SQLite文件中的数据进行互相转换&#xff0c;极大地方便了开发者在数据服务方面的开发。 1. 创建CoreData 在文件创建区下&#xff0c;选择【Core Data】下的【Data Model】 输入CoreData的文件名Model.x…

Core Data 概述

Core Data 概述 转载自&#xff1a; http://www.cocoachina.com/newbie/basic/2013/0911/6981.html Core Data可能是OS X和iOS里面最容易被误解的框架之一了&#xff0c;为了帮助大家理解&#xff0c;我们将快速的研究Core Data&#xff0c;让大家对它有一个初步的了解&#x…

CoreData相关01 基础及运用:添加、查询、过滤、排序、分页

CoreData CoreData中几乎不用写数据库操作语句就能完成数据的本地化存储。 CoreData和iOS中的模型对象相联系在一起&#xff0c;只需要操作模型对象的增删改查就可以完成数据的增删改查&#xff0c;不用写SQL语句。 CoreData的存储方式 SQLite NSSQLiteStoreType XML NSXML…

JVM原理分析

JVM原理分析 为什么Java是一种跨平台语言 1、不同系统的JDK下载 JDK里面有&#xff1a;Jre和Jvm&#xff0c;其中就有JVM指令集的不同 JVM主要结构&#xff1a; 栈、堆、方法区、程序计数器、本地方法栈 mian方法的执行 通过类装载子系统进入JVM 其中栈中存放线程 来一个…

JVM实现原理

JVM原理 1、概念简介2、为什么要学习JVM虚拟机&#xff1f;3、JVM怎么学&#xff1f;3.1 内存管理1、jvm运行时数据区 1、概念简介 JVM&#xff1a;JAVA虚拟机JRE&#xff1a;Java运行环境 JREJVM虚拟机Java核心类库支持文件JDK&#xff1a;Java开发工具包 JDKJREJava工具Java…

【JVM调优】JVM原理与性能调优

一、参考资料 今日头条https://www.toutiao.com/i7007696978586976805

JVM原理和调优的理解和学习

JVM原理和调优的理解和学习 一、详解JVM内存模型二、JVM中一次完整的GC流程是怎样的三、GC垃圾回收的算法有哪些四、简单说说你了解的类加载器五、双亲委派机制是什么&#xff0c;有什么好处&#xff0c;怎么打破六、说说你JVM调优的几种主要的JVM参数七、JVM调优八、类加载的机…

JVM原理-jvm内存模型

一、jvm内存模型 结构图 JVM包含两个子系统和两个组件 Class loader(类装载子系统) 根据给定的全限定名类名(如&#xff1a;java.lang.Object)来装载class文件到 Runtime data area运行时数据区中的method area方法区中Execution engine(执行引擎) 执行classes中的指令Runt…

JVM原理-垃圾回收机制及算法

JVM原理-jvm内存模型 jvm内存模型 一、垃圾回收机制算法 1、 判断对象是否回收算法 垃圾收集器在做垃圾回收的时候&#xff0c;首先需要判定的就是哪些内存是需要被回收的&#xff0c;哪些对象是存活的&#xff0c;是不可以被回收的&#xff1b;哪些对象已经死掉了&#xf…

jvm面试原理

1、什么是JVM JVM是Java Virtual Machine&#xff08;Java虚拟机&#xff09;的缩写&#xff0c;JVM是一种用于计算设备的规范&#xff0c;它是一个虚构出来的计算机&#xff0c;是通过在实际的计算机上仿真模拟各种计算机功能来实现的。Java虚拟机包括一套字节码指令集、一组…

JVM原理和JVM内存的整理

JVM原理及JVM内存 JVM原理及JVM内存概念这么说1.JVM的基本过程2.JVM的中的“解释”原理&#xff0c;三个重要机制3.JVM的体系结构4.运行时数据区JVM垃圾回收 JVM原理及JVM内存 之前看了许多JVM原理的文章、写作的大牛们都讲的很透彻&#xff0c;但是私下觉得&#xff1a;写得详…

JVM原理和调优(读这一篇就够了)

前言 抛2个问题&#xff1a; 1、export JAVA_OPTS"-Xms256m -Xmx512m -Xss256m -XX:PermSize512m -XX:MaxPermSize1024m -Djava.rmi.server.hostname136.64.45.24 -Dcom.sun.management.jmxremote.port9315 -Dcom.sun.management.jmxremote.sslfalse -Dcom.sun.manageme…

JVM工作原理

JVM的生命周期 &#xff08;1&#xff09;两个概念&#xff1a;JVM实例和JVM执行引擎实例 JVM实例对应了一个独立运行的java程序&#xff0c;它是进程级别的 JVM执行引擎实例则对应了属于用户运行程序的线程&#xff0c;它是线程级别的 &#xff08;2&#xff09;VM实例的诞生…

JVM原理与实战

JVM原理 类加载流程和内存分配栈帧操作一、JVM垃圾回收算法主动加载的几种方式?符号引用和直接引用1.1 什么是垃圾(Garbage Collection)回收?1.2 引用计数法(Reference Conting)1.3 标记清除法 *(Mark - Sweep)1.4 复制算法 *(Copying)1.4.1 复制算法在JVM中的应用1.…

jvm原理与性能调优

文章目录 一、JVM内存结构 1.运行时数据区 2.直接内存 二、JVM中的对象 1.对象的创建 2.对象的内存布局 3.对象的访问定位 三、垃圾回收算法和垃圾回收器 1. 如何判断对象是已死 2.分代回收理论 3.垃圾回收算法 4.垃圾收集器 四、JVM执行子系统 1.Class文件结构 2.类加载机制 3…

什么是JVM?深入解析JVM原理!

一、JVM是什么? JVM是Java Virtual Machine(Java虚拟机)的缩写,是通过在实际的计算机上仿真模拟各种计算机功能来实现的。由一套字节码指令集、一组寄存器、一个栈、一个垃圾回收堆和一个存储方法域等组成。JVM屏蔽了与操作系统平台相关的信息,使得Java程序只需要生成在J…

全面阐述JVM原理

一 JVM入门 1. 什么是JVM JVM是Java Virtual Machine&#xff08;Java虚拟机&#xff09;的缩写&#xff0c;JVM是一种用于计算设备的规范&#xff0c;它是一个虚构出来的计算机&#xff0c;是通过在实际的计算机上仿真模拟各种计算机功能来实现的。Java虚拟机包括一套字节码…

JVM原理

JVM原理 一.jvm简介 JVM是Java Virual Machine&#xff08;Java虚拟机&#xff09;的缩写&#xff0c;JVM是一种用于计算设备的规范&#xff0c;他是一个虚构出来的计算机&#xff0c;是通过在实际的计算机上仿真模拟计算机功能来实现的。Java虚拟机包括一套字节码指令集、一组…