2017-04-20 71 views
0

我是新來的核心數據..如何刪除核心數據中的條目

我知道如何存儲和項目。

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

} 

}

但我堅持建立以清除這一核心數據的數據庫的方法..有誰知道怎麼樣?

+0

您是否要求刪除所有表?放一張桌子?或從表中刪除一個字段? – Brandon

+0

查看此鏈接http://stackoverflow.com/questions/1077810/delete-reset-all-entries-in-core-data –

+0

[從Core-Data中刪除特定項/行](http:// stackoverflow.com/questions/6524876/removing-a-specific-entry-row-from-core-data) – shallowThought

回答

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