CoreData清空数据库
-
清空数据库可以使用删除文件的方式
-
通过沙盒路径进入到沙盒可以看到数据库文件有三个,我们逐一删除便可
-
代码中的kFileName是一个宏 表示创建的数据库文件名
NSFileManager *fileManager = [NSFileManager defaultManager]; NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; //沙盒中三个文件 NSString *filePath1 = [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.db",kFileName]]; NSString *filePath2 = [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.db-shm",kFileName]]; NSString *filePath3 = [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.db-wal",kFileName]]; NSError *error; BOOL success = [fileManager removeItemAtPath:filePath1 error:&error]; [fileManager removeItemAtPath:filePath2 error:nil]; [fileManager removeItemAtPath:filePath3 error:nil]; if (success) { NSLog(@"Remove fiel:%@ Success!",kFileName); } else { NSLog(@"Could not delete file -:%@ ",[error localizedDescription]); }
CoreData清空数据库实际开发中注意事项
1.从原则上来讲,清空数据库时直接删除数据库文件的效率和便利性远大于先从数据库中取数据然后逐一删除2.但是虽然删除了数据库文件,继续从CoreData Stack技术栈堆中查询数据仍然可以查询到,这是因为在上一次的查询过程中,数据库中的数据已经被缓存到内存。3.网上有很多示例,要想清除CoreData缓存,ARC下直接设置CoreDataStack元素为nil
kManagedObjectContext.managedObjectContext =nil;
kManagedObjectContext.persistentStoreCoordinator =nil;
kManagedObjectContext.persistentStore =nil;
我认为这样写是不专业的,如果需要再次使用就必须要重新初始化CoreData Stack,非常损耗性能
4.由于之前讲解过CoreData Stack中真正进行储存数据操作的是NSPersistentStore(存储器),所以这里只需要移除存储器再重新添加便可
NSURL *url = [[kManagedObjectContextgetDocumentsUrl]URLByAppendingPathComponent:@"mysql.db"isDirectory:YES];
NSLog(@"%@",kManagedObjectContext.persistentStoreCoordinator.persistentStores);
[kManagedObjectContext.persistentStoreCoordinatorremovePersistentStore:kManagedObjectContext.persistentStoreCoordinator.persistentStores[0]error:nil];
[kManagedObjectContext.persistentStoreCoordinatoraddPersistentStoreWithType:NSSQLiteStoreTypeconfiguration:nilURL:urloptions:nilerror:nil];
[self.tableViewreloadData];