07-CoreData清除所有数据


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


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值