iOS数据持久化iOSiOS开发资源

缓存与删除

2015-09-06  本文已影响2460人  sydie

归档

    // 地址拼接
    NSString *docData = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    
    // 创建数据
    NSArray *array = @[@10,@"name",@"picture"];
    // 获取最终地址
    NSString *data = [docData stringByAppendingPathComponent:@"data.plist"];
   
    // 存
    [array writeToFile:data atomically:YES];
    // 地址拼接
    NSString *docData = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    // 获取最终地址
    NSString *data = [docData stringByAppendingPathComponent:@"data.plist"];
    
    NSArray *array = [NSArray arrayWithContentsOfFile:data];
// 归档
NSString *homeDictionary = NSHomeDirectory();//获取根目录 
NSString *homePath  = [homeDictionary stringByAppendingPathComponent:@"atany.archiver"];//添加储存的文件名  
BOOL flag = [NSKeyedArchiver archiveRootObject:@”归档” toFile:homePath];//归档一个字符串
// 接档
[NSKeyedUnarchiver unarchiveObjectWithFile:homePath]  
//准备数据  
CGPoint point = CGPointMake(1.0, 2.0);  
NSString *info = @"坐标原点";  
NSInteger value = 10;  
NSString *multiHomePath = [NSHomeDirectory() stringByAppendingPathComponent:@"multi.archiver"];  
NSMutableData *data = [[NSMutableData alloc]init];  
NSKeyedArchiver *archvier = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];  
  
//对多个对象进行归档  
[archvier encodeCGPoint:point forKey:@"kPoint"];  
[archvier encodeObject:info forKey:@"kInfo"];  
[archvier encodeInteger:value forKey:@"kValue"];  
[archvier finishEncoding];  
[data writeToFile:multiHomePath atomically:YES];  
NSMutableData *dataR = [[NSMutableData alloc]initWithContentsOfFile:multiHomePath];  
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:dateR];  
CGPoint pointR = [unarchiver decodeCGPointForKey:@"kPoint"];  
NSString *infoR = [unarchiver decodeObjectForKey:@"kInfo"];  
NSInteger valueR = [unarchiver decodeIntegerForKey:@"kValue"];  
[unarchiver finishDecoding];  
NSLog(@"%f,%f,%@,%d",pointR.x,pointR.y,infoR,valueR);  
Encodes the receiverusing a given archiver
// 通过一个给定的archiver把消息接收者进行编码。当接收到encodeObject消息的时候,类终端encodeWithCoder方法被调用。
Returns an objectinitialized from data in a given unarchiver. (required)
// 从一个给定unarchiver的数据中返回一个初始化对象。
// 存储
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:@"jack" forKey:@"name"];
[defaults setBool:YES forKey:@"isOk"];
// 同步
[defaults synchronize];
// 读取
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *name = [defaults objectForKey:@"name"];
NSLog(@"%@",name);
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    CXLClearCacheCell *cell = [tableView dequeueReusableCellWithIdentifier:setId];
 
    return cell;
}
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        // 添加菊花
        UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        
        // 开始动画
        [activityIndicator startAnimating];
        [self addSubview:activityIndicator];
        
        self.loadingView = activityIndicator;
        
        self.textLabel.text = @"清除缓存";
        [self getCacheSize];
    }
    return self;
}
// 布局
- (void)layoutSubviews
{
    [super layoutSubviews];
    [self.textLabel sizeToFit];
    self.textLabel.centerY = self.height*0.5;
    self.loadingView.x = CGRectGetMaxX(self.textLabel.frame) + CXLMargin;
    self.loadingView.centerY = self.height*0.5;
}
@interface NSString (Extension)
- (NSInteger)fileSize;
- (NSString *)fileSizeString;
@end
- (NSInteger)fileSize
{
    // 创建文件管理者
    NSFileManager *manager = [NSFileManager defaultManager];
    // 先判断文件是否存在
    BOOL isDirectory = NO;
    BOOL exist = [manager fileExistsAtPath:self isDirectory:&isDirectory];
    // 如果文件不存在
    if (exist==NO) return 0;
    
    // 如果文件存在  判断为文件夹还是文件
    if (isDirectory) {
        // 计算文件大小。拿到了完整路径
        NSInteger fileSize = 0;
        // 用完整路径查询所有的文件的大小,返回为数组
        NSArray *pathArray = [manager subpathsAtPath:self];
        
        // 遍历数组,将获得的数组字符串拼接到file上
        for (NSString *path in pathArray) {
            // 获得完整地址
            NSString *fulSubPath = [self stringByAppendingPathComponent:path];
            // 获得属性
            NSDictionary *attrs = [manager attributesOfItemAtPath:fulSubPath error:nil];
            // 过滤掉文件夹
            if ([attrs[NSFileType] isEqualToString:NSFileTypeDirectory]) continue;
            // 将属性中的fileSize相加。
            fileSize += [attrs[NSFileSize] integerValue];
    }
        return fileSize;

    }
    return [[manager attributesOfItemAtPath:self error:nil][NSFileSize] integerValue];
}
- (NSString *)fileSizeString
{
    NSInteger fileSize = self.fileSize;
    // 设定一个单位
    CGFloat unit = 1000.0;
    // 对fileSize进行判断
    if (fileSize>= unit * unit * unit) {
        return [NSString stringWithFormat:@"%.1fGB",fileSize/(unit*unit*unit)];
    }else if (fileSize>= unit*unit) {
        return [NSString stringWithFormat:@"%.1fMB",fileSize/(unit*unit)];
    }else if (fileSize>= unit){
        return [NSString stringWithFormat:@"%.1fKB",fileSize/unit];
    }else
    {
        return [NSString stringWithFormat:@"%zdB",fileSize];
    }
    
}
// 获取缓存大小
- (void)getCacheSize
{
 dispatch_async(dispatch_get_global_queue(0, 0), ^{
        // 应用沙盒地址,返回的是一个数组
        NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        // 拼接路径
        NSString *file = [caches stringByAppendingPathComponent:@"default/com.hackemist.SDWebImageCache.default"].fileSizeString;
         // 计算缓存大小只是为了在label中显示。
        NSString *str = [NSString stringWithFormat:@"清除缓存(%@)",file];
            dispatch_async(dispatch_get_main_queue(), ^{
        // 回到主线程
        self.textLabel.text = str;
        [self.loadingView removeFromSuperview];   
        });      
    });
}
   dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSString *cachPath = [ NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES ) objectAtIndex : 0 ];
       
       NSArray *files = [[ NSFileManager defaultManager ] subpathsAtPath :cachPath];
       
       for ( NSString *p in files) {
           NSError *error;
           NSString *path = [cachPath stringByAppendingPathComponent :p];
           if ([[ NSFileManager defaultManager ] fileExistsAtPath :path]) {
               [[ NSFileManager defaultManager ] removeItemAtPath :path error :&error];
           }
       }dispatch_async(dispatch_get_main_queue(), ^{
        // 创建cell
       CXLClearCacheCell *cell = (CXLClearCacheCell *) [tableView cellForRowAtIndexPath:indexPath];
       // 取消遮盖
       [SVProgressHUD showSuccessWithStatus:@"清除缓存成功"];
          // 在cell中写的一个删除后的方法 
      [cell regist];
       });
  // 清除缓存代码
    [[SDImageCache sharedImageCache] clearDiskOnCompletion:^{   
    // 创建cell
        CXLClearCacheCell *cell = (CXLClearCacheCell *) [tableView cellForRowAtIndexPath:indexPath];
       // 取消遮盖
        [SVProgressHUD showSuccessWithStatus:@"清除缓存成功"];       
        [cell regist];
   }];
上一篇 下一篇

猜你喜欢

热点阅读