CoreData 增删改查

#pragma mark - Core Data Methods

- (void)insertObjectWithFileName:(NSString *)fileName

{

/**

SQL新增记录的过程

1. 拼接一个INSERT的SQL语句

2. 执行SQL

*/

// 1. 实例化并让context“准备”将一条个人记录增加到数据库

ReaderDocument *document = [NSEntityDescription insertNewObjectForEntityForName:kOAPDFDocumentinManagedObjectContext:self.managedObjectContext];

// 2. 设置个人信息

document.fileName = fileName;

// 3. 保存(让context保存当前的修改)

if ([self.managedObjectContext save:nil]) {

NSLog(@"新增成功");

} else {

NSLog(@"新增失败");

}

}

- (NSMutableArray *)getObjectsWithPredicate:(NSString *)predicate

{

// 1. 实例化一个查询(Fetch)请求

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:kOAPDFDocument];

// 3. 条件查询,通过谓词来实现的

//    request.predicate = [NSPredicate predicateWithFormat:@"age < 60 && name LIKE ‘*五‘"];

// 在谓词中CONTAINS类似于数据库的 LIKE ‘%王%‘

//    request.predicate = [NSPredicate predicateWithFormat:@"phoneNo CONTAINS ‘1‘"];

// 如果要通过key path查询字段,需要使用%K

//    request.predicate = [NSPredicate predicateWithFormat:@"%K CONTAINS ‘1‘", @"phoneNo"];

// 直接查询字表中的条件

// 2. 让_context执行查询数据

NSArray *array = [self.managedObjectContext executeFetchRequest:request error:nil];

//    for (OAPDFDocument *pdf in array) {

//        NSLog(@"\nfielName:%@ \nfilePath:%@ \nfileSize:%@", pdf.fileName, pdf.filePath, pdf.fileSize);

// 在CoreData中,查询是懒加载的

// 在CoreData本身的SQL查询中,是不使用JOIN的,不需要外键

// 这种方式的优点是:内存占用相对较小,但是磁盘读写的频率会较高

//        for (Book *b in p.books) {

//            NSLog(@"%@ %@ %@", b.name, b.price, b.author);

//        }

//    }

//    for (Book *b in array) {

//        NSLog(@"%@ %@ %@", b.name, b.price, b.author);

//    }

return [NSMutableArray arrayWithArray:array];

}

- (void)editObjectsWithPredicate:(NSPredicate *)predicate withState:(NSNumber *)state

{

// 1. 实例化一个查询(Fetch)请求

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:kOAPDFDocument];

// 2. 条件查询,通过谓词来实现的

request.predicate = predicate;

// 在谓词中CONTAINS类似于数据库的 LIKE ‘%王%‘

//    request.predicate = [NSPredicate predicateWithFormat:@"phoneNo CONTAINS ‘1‘"];

// 如果要通过key path查询字段,需要使用%K

//    request.predicate = [NSPredicate predicateWithFormat:@"%K CONTAINS ‘1‘", @"phoneNo"];

// 直接查询字表中的条件

// 3. 让_context执行查询数据

NSArray *array = [self.managedObjectContext executeFetchRequest:request error:nil];

for (ReaderDocument *pdf in array) {

// 3.1修改公文阅读状态

pdf.fileTag = state;

// 3.2修改公文最新打开日期

NSFileManager* fileMngr = [NSFileManager defaultManager];

NSDictionary* attributes = [fileMngr attributesOfItemAtPath:pdf.fileURL error:nil];

pdf.lastOpen = (NSDate *)[attributes objectForKey:NSFileModificationDate];

// 3.3获取并保存,该文件的首页缩略图

UIImage *thumbImage = [pdf imageFromPDFWithDocumentRef:pdf.fileURL];

pdf.thumbImage = UIImagePNGRepresentation(thumbImage);

[self.collectionView reloadData];

break;

}

// 4. 通知_context修改数据是否成功

if ([self.managedObjectContext save:nil]) {

NSLog(@"修改成功");

} else {

NSLog(@"修改失败");

}

}

- (void)removeObjectsWithPredicate:(NSString *)predicate

{

// 1. 实例化查询请求

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:kOAPDFDocument];

// 2. 设置谓词条件

//    request.predicate = [NSPredicate predicateWithFormat:@"name = ‘张老头‘"];

request.predicate = [NSPredicate predicateWithFormat:predicate];

// 3. 由上下文查询数据

NSArray *result = [self.managedObjectContext executeFetchRequest:request error:nil];

// 4. 输出结果

for (ReaderDocument *pdf in result) {

// 删除一条记录

[self.managedObjectContext deleteObject:pdf];

BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:pdf.filePath];

if (fileExists) {

[self removeFileWithName:pdf.fileName];

}else{

NSLog(@"File:%@ is not exist!",pdf.fileName);

}

//        break;

}

// 5. 通知_context保存数据

if ([self.managedObjectContext save:nil]) {

NSLog(@"删除%lu文件成功",(unsigned long)[result count]);

} else {

NSLog(@"删除失败");

}

}

- (void)removeFileWithName:(NSString *)fileName

{

NSFileManager *fileManager = [NSFileManager defaultManager];

NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

NSString *filePath = [documentsPath stringByAppendingPathComponent:fileName];

NSError *error;

BOOL success = [fileManager removeItemAtPath:filePath error:&error];

if (success) {

NSLog(@"Remove fiel:%@ Success!",fileName);

}

else

{

NSLog(@"Could not delete file -:%@ ",[error localizedDescription]);

}

}

时间: 2024-08-01 03:52:17

CoreData 增删改查的相关文章

iOS CoreData 增删改查详解

最近在学习CoreData, 因为项目开发中需要,特意学习和整理了一下,整理出来方便以后使用和同行借鉴.目前开发使用的Swift语言开发的项目.所以整理出来的是Swift版本,OC我就放弃了. 虽然Swift3 已经有了,目前整理的这个版本是Swift2 的.Swift 3 的话有些新特性. 需要另外调整,后续有时间再整理. 继承CoreData有两种方式: 创建项目时集成 这种方式是自动继承在AppDelegate里面,调用的使用需要通过UIApplication的方式来获取AppDelega

IOS - CoreData 增删改查

#pragma mark - Core Data Methods - (void)insertObjectWithFileName:(NSString *)fileName { /** SQL新增记录的过程 1. 拼接一个INSERT的SQL语句 2. 执行SQL */ // 1. 实例化并让context“准备”将一条个人记录增加到数据库 ReaderDocument *document = [NSEntityDescription insertNewObjectForEntityForNam

Swift CoreData 增删改查

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Menlo; color: #1e9421; background-color: #ffffff } p.p2 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica; background-color: #ffffff; min-height: 14.0px } p.p3 { margin: 0.0px 0.0px 0.0px 0

CoreData的增删改查和数据迁移示例

作为管理器,最基本的功能就是增删改查了. 1.插入 AppDelegate *app = [[UIApplication sharedApplication] delegate]; NSManagedObjectContext *context = [app managedObjectContext]; NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:@"entity

IOS之分析网易新闻存储数据(CoreData的使用,增删改查)

用过网易新闻客户端的朋友们都知道,获取新闻列表时有的时候他会请求网络有时候不会,查看某条新闻的时候再返回会标注已经查看的效果,接下来分析一下是如何实现的. 首先: 1.网易新闻用CoreData存储了新闻列表,因为我打开网易新闻的Documents时看到了三个文件: newsapp.sqlite,newsapp.sqlite-shm,newsapp.sqlite-wal:这三个文件是你在用CoreData时自动生成的.所以我确定他是用coredata存储的数据而不是sqlite数据库.(Core

CoreData的简单使用(二)数据的增删改查,轻量级的版本迁移

上一篇中我们已经使用CoreData创建了一个SQLite数据库 CoreData的简单使用(一)数据库的创建 现在对数据库进行数据的CRUD(增删改查) 1.Data Model 的设置 创建一个DataModel,取名CRUD.xcdatamodeld,添加Entity(Library和Book),添加属性,在Book中设置和Library的关联关系(一个Book可以存放在一个Library里) Book的属性和关联关系(选择Destination为Library,关系名称取名为librar

ios CoreData框架的使用,对上下文数据的增删改查,表与表之间的关联,1对多,1对1,谓词查询,多表连接

这里是只是代码,因为博客插入图片效果不是很好,我自己写的总结比较详细,有兴趣的朋友可以在评论里留下邮箱,我收到后会发给大家. 转载注明出处,重视原创者的劳动成果,谢谢! - (void)viewDidLoad { [super viewDidLoad]; [self _creatTable];//插入数据 //    [self _query];// 查询数据 // KVC很霸道,即使readonly通过kvc也可赋值,kvo精华 //    Book * book = [[Book alloc

CoreData 入门使用 增删改查 swift

首先新建一个 点击新建的testInfo.xcdatamodeld 会出现这么个界面 创建完testInfo.xcdatamodeld之后 AppDelegate 会自动帮你添加支持coredata的代码 有兴趣的自己研究 首先 使用coredata 存储数据 1.创建表 2.创建字段 3.创建对应字段的模型类 就足够了 创建表 点击 然后出现 添加字段 .................... 创建对应字段的模型  command+n  都勾上之后会自动帮你创建一个类  好 一切准备完毕.  

iOS CoreData (一) 增删改查

代码地址如下:<br>http://www.demodashi.com/demo/11041.html Core Data是iOS5之后才出现的一个框架,本质上是对SQLite的一个封装,它提供了对象-关系映射(ORM)的功能,即能够将OC对象转化成数据,保存在SQLite数据库文件中,也能够将保存在数据库中的数据还原成OC对象,通过CoreData管理应用程序的数据模型,可以极大程度减少需要编写的代码数量! ##一.运行效果##二.程序实现 1. 首先创建一个coreData 模型文件:系统