how to remove all objects from Core Data

前端 未结 7 1446
我寻月下人不归
我寻月下人不归 2020-12-09 23:04

how can I remove all objects? I know I can remove one by

[managedObjectContext deleteObject:objToDelete];

is it possible to delete all wit

7条回答
  •  悲&欢浪女
    2020-12-09 23:28

    When you remove all the cache and documents, you are deleting the database. Not is necesary call to managedObjectContext

    NSArray *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSArray *caches = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSMutableArray *paths = [NSMutableArray array];
    [paths addObjectsFromArray:documents];
    [paths addObjectsFromArray:caches];
    for (NSUInteger i = 0; i < [paths count]; i++) {
        NSString *folderPath = [paths objectAtIndex:i];
        NSLog(@"Attempting to remove contents for: %@", folderPath);
        //Remove all cached data in the local app directory
        NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderPath error:&error];
        for (NSString *strName in dirContents) {
            [[NSFileManager defaultManager] removeItemAtPath:[folderPath stringByAppendingPathComponent:strName] error:&error];
            if (error != nil) {
                NSLog(@"Error removing item: %@ : %@", strName, error.description);
            } else {
                NSLog(@"Removed item: %@", strName);
            }
        }
    }
    

提交回复
热议问题