You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CoreData保存失败报错NSSQLiteErrorDomain Code=101,设备内存磁盘耗尽

CoreData 保存失败(NSSQLiteErrorDomain Code=101)排查与解决

问题根因

报错Error Domain=NSSQLiteErrorDomain Code=101 "(null)" UserInfo={EncryptedStoreErrorMessage=unknown error},结合设备可用RAM、磁盘空间均为0B的情况,核心原因是设备存储完全耗尽——SQLite(CoreData底层依赖)无法写入数据,加密存储层因此抛出未知错误,同时内存耗尽会进一步加剧操作失败概率。

解决步骤

  • 优先处理存储耗尽问题
    在执行CoreData操作前,先检查设备剩余磁盘空间,提前拦截异常:

    NSError *fsError;
    NSDictionary *fsAttrs = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&fsError];
    if (fsAttrs) {
        unsigned long long freeSpace = [fsAttrs[NSFileSystemFreeSize] unsignedLongLongValue];
        // 设定最低存储阈值,比如100MB
        if (freeSpace < 100 * 1024 * 1024) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"存储空间不足" 
                                                                           message:@"请清理设备存储空间后再使用" 
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
            [self presentViewController:alert animated:YES completion:nil];
            return;
        }
    }
    

    同时引导用户删除无用文件或应用释放空间。

  • 优化CoreData保存逻辑
    增加前置检查,避免无意义的保存尝试,同时完善错误上报信息:

    // 无变更直接跳过
    if (![context hasChanges]) return;
    
    // 先确认存储可用再执行保存
    if (!self.isDeviceStorageEnough) {
        NSLog(@"存储空间不足,无法保存数据");
        return;
    }
    
    NSError *saveError;
    if (![context save:&saveError]) {
        // 上报时补充存储、内存状态,方便排查
        NSDictionary *extraInfo = @{
            @"freeDiskSpace": @(self.currentFreeDiskSpace),
            @"freeRAM": @(self.currentFreeRAM)
        };
        [[FIRCrashlytics crashlytics] recordError:saveError withAdditionalUserInfo:extraInfo];
    }
    
  • 缓解内存耗尽问题
    清理不必要的缓存,减少内存占用:

    // 清理系统URL缓存
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    // 清理自定义缓存(比如图片缓存)
    [self.customImageCache removeAllObjects];
    

    同时避免一次性加载大量CoreData对象,改用分批查询、分页获取的方式。

  • 加密存储层检查
    确认你使用的加密存储库(如EncryptedCoreData)与当前CoreData版本兼容,同时检查加密密钥是否正常加载,确保加密流程能正常执行。

内容的提问来源于stack exchange,提问作者Wide Angle Technology

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 03:45:35