如何删除核心数据中的条目

时间:2017-04-20 13:19:08

标签: ios objective-c core-data

我是核心数据的新手..

我知道如何存储和物品。

- (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]) {

}

}

但我仍然坚持创建一种方法来清除这个核心数据数据库。有谁知道怎么做?

2 个答案:

答案 0 :(得分:0)

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");
}

答案 1 :(得分:0)

使用此

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];
    }
}