美文网首页
清除缓存

清除缓存

作者: 舒耀 | 来源:发表于2015-05-21 10:21 被阅读237次

.h文件
@interface WdCleanCaches : NSObject

/**

  • 返回path路径下文件的文件大小。
    */
  • (double)sizeWithFilePaht:(NSString *)path;

/**

  • 删除path路径下的文件。
    */
  • (void)clearCachesWithFilePath:(NSString *)path;

/**

  • 获取沙盒Library的文件目录。
    */
  • (NSString *)LibraryDirectory;

/**

  • 获取沙盒Document的文件目录。
    */
  • (NSString *)DocumentDirectory;

/**

  • 获取沙盒Preference的文件目录。
    */
  • (NSString *)PreferencePanesDirectory;

/**

  • 获取沙盒Caches的文件目录。
    */
  • (NSString *)CachesDirectory;

.m文件

  • (NSString *)LibraryDirectory
    {
    return [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
    }

  • (NSString *)DocumentDirectory
    {
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    }

  • (NSString *)PreferencePanesDirectory
    {
    return [NSSearchPathForDirectoriesInDomains(NSPreferencePanesDirectory, NSUserDomainMask, YES) lastObject];
    }

  • (NSString *)CachesDirectory
    {
    return [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    }
    // 按路径清除文件

  • (void)clearCachesWithFilePath:(NSString *)path
    {
    NSFileManager *mgr = [NSFileManager defaultManager];
    if ([mgr fileExistsAtPath:path]) {
    NSArray *childrenFiles = [mgr subpathsAtPath:path];
    for (NSString *fileName in childrenFiles) {
    //如有需要加入条件,过滤掉不想删除的文件
    NSString *absolutePath = [path stringByAppendingPathComponent:fileName];
    [mgr removeItemAtPath:absolutePath error:nil];
    }
    }
    }

  • (double)sizeWithFilePaht:(NSString *)path
    {
    // 1.获得文件夹管理者
    NSFileManager *mgr = [NSFileManager defaultManager];

    // 2.检测路径的合理性
    BOOL dir = NO;
    BOOL exits = [mgr fileExistsAtPath:path isDirectory:&dir];
    if (!exits) return 0;

    // 3.判断是否为文件夹
    if (dir) { // 文件夹, 遍历文件夹里面的所有文件
    // 这个方法能获得这个文件夹下面的所有子路径(直接\间接子路径)
    NSArray *subpaths = [mgr subpathsAtPath:path];
    int totalSize = 0;
    for (NSString *subpath in subpaths) {
    NSString *fullsubpath = [path stringByAppendingPathComponent:subpath];

          BOOL dir = NO;
          [mgr fileExistsAtPath:fullsubpath isDirectory:&dir];
          if (!dir) { // 子路径是个文件
              NSDictionary *attrs = [mgr attributesOfItemAtPath:fullsubpath error:nil];
              totalSize += [attrs[NSFileSize] intValue];
          }
      }
      return totalSize / (1000 * 1000.0);
    

    } else { // 文件
    NSDictionary *attrs = [mgr attributesOfItemAtPath:path error:nil];
    return [attrs[NSFileSize] intValue] / (1000 * 1000.0);
    NSLog(@"+++++++++++++++可清空数据%f++++++++++++++++++",[attrs[NSFileSize] intValue] / (1000 * 1000.0));
    }
    }

@end

相关文章

网友评论

      本文标题:清除缓存

      本文链接:https://www.haomeiwen.com/subject/oiilqttx.html