Core Data 无 Unique 唯一检查, 比较简陋, 但用起来简单
- 创建项目时勾选 use core data / 在项目中add 一个新的
-
新建项目一起创建
-
在已有项目中添加 (需要复制有coredata 的 AppDelegate代码)
2.创建数据模块
3.创建对应的类
这时候创建不是右键创建,通过主菜单 Editor -> Create NSManagedObject Subclass
4.自动会为数据模块创建两个类文件
注意,不要把类文件加到 Compile Sources 中,会出现重复错误,如果创建文件后拖拽到文件夹会自动被添加到其中,请手动移除
- 获得基础参数:
appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
context = appDelegate.persistentContainer.viewContext;
6.添加数据
VideoImgCache* cacheAdd = [NSEntityDescription insertNewObjectForEntityForName:@"VideoImgCache" inManagedObjectContext:context];
cacheAdd.key = key;
cacheAdd.imagePath = localPath.relativeString;
[appDelegate saveContext];
- 删除所有数据
NSEntityDescription *cacheGet= [NSEntityDescription entityForName:@"VideoImgCache" inManagedObjectContext:context];
searchRequest = [[NSFetchRequest alloc] init];
[searchRequest setEntity:cacheGet];
poolCache = [context executeFetchRequest :searchRequest error:nil];
for (VideoImgCache* cacheUnit in poolCache) {
[context deleteObject:cacheUnit];
}
- 查询数据
NSEntityDescription *cacheGet= [NSEntityDescription entityForName:@"VideoImgCache" inManagedObjectContext:context];
searchRequest = [[NSFetchRequest alloc] init];
[searchRequest setEntity:cacheGet];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"key=%@",key];
searchRequest.predicate = predicate;
poolCache = [context executeFetchRequest :searchRequest error:nil];
for (VideoImgCache* cacheUnit in poolCache) {
NSLog(@"cacheUnit name:%@ %@",cacheUnit.key, cacheUnit.imagePath );
}
- 线程,这些代码,尤其是写入/删除数据,必须放入主线程处理,用下面代码来确保在主线中中运行
dispatch_async(dispatch_get_main_queue(), ^{
//在这写主线程代码
});