如何删除核心数据中的条目
Posted
技术标签:
【中文标题】如何删除核心数据中的条目【英文标题】:How to delete entries in core data 【发布时间】:2017-04-20 13:19:08 【问题描述】:我是核心数据的新手..
我知道如何存储和物品。
- (void)dbSave:(NSString *)uri withContent:(NSDictionary *)content withExpiry:(double)date
Cache *cache = [self dbLoad:uri];
if (cache == nil)
cache = [NSEntityDescription insertNewObjectForEntityForName:@"Cache" inManagedObjectContext:[self managedObjectContext]];
double time = (double) [[NSDate date] timeIntervalSince1970] + date;
[cache setLocal:uri];
[cache setTime:@(time)];
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:content forKey:@"data"];
[archiver finishEncoding];
[cache setData:data];
NSError *error;
if (![[self managedObjectContext] save:&error])
但我坚持创建一种方法来清除这个核心数据库。有人知道怎么做吗?
【问题讨论】:
您是否要求删除所有表格?丢一张桌子?还是从表中删除一个字段? 查看此链接***.com/questions/1077810/… Removing a specific entry/row from Core-Data的可能重复 @Brandon 实体下名为缓存的所有内容 【参考方案1】:NSManagedObjectContext *managedObjectContext=[appDelegate managedObjectContext];
NSFetchRequest *fetchRequest=[NSFetchRequest fetchRequestWithEntityName:@"entity"];
NSArray* currentRecord = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
if (currentRecord.count)
for (NSManagedObject *obj in currentRecord)
[managedObjectContext deleteObject:obj];
NSError * error = nil;
if (![managedObjectContext save:&error])
NSLog(@"Can't save ! %@ %@",error,[error localizedDescription]);
else
NSLog(@"Data deleted");
【讨论】:
【参考方案2】:使用这个
NSManagedObjectContext *managedContext = [[APP_DELEGATE dbManagerObj] newPrivateContext];
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Cache"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"isUserData = %@",[NSNumber numberWithBool:true]];
[fetchRequest setPredicate:predicate];
if (IS_ios9_ANDABOVE)
NSBatchDeleteRequest *batchDeleteRequest = [[NSBatchDeleteRequest alloc]initWithFetchRequest:fetchRequest];
[[[APP_DELEGATE dbManagerObj]persistentStoreCoordinator]executeRequest:batchDeleteRequest withContext:managedContext error:nil];
else
NSArray *userRelatedDay = [managedContext executeFetchRequest:fetchRequest error:nil];
for (NSManagedObject *object in userRelatedDay)
[managedContext deleteObject:object];
【讨论】:
以上是关于如何删除核心数据中的条目的主要内容,如果未能解决你的问题,请参考以下文章