iOS 本地存储,缓存和清除

来源:互联网 发布:西安市汇知中学 编辑:程序博客网 时间:2024/05/22 01:27

在开发APP的时候,通常会用到本地的数据存储,减少流量的使用和服务器的压力.下面几种常用的方法

1.在缓存图片的时候,SDWebImage是比较好用的一种方式,操作简单,只需要一个图片地址,设置占位图.记住设置options为SDWebImageRefreshCached

存:        [self.imagesView sd_setImageWithURL:[NSURL URLWithString:model.product_img] placeholderImage:[UIImage imageNamed:@"product_list_placeholder"] options:SDWebImageRefreshCached];

删:一般是全部删除,

[[SDImageCache sharedImageCache] clearMemory];//可不写
    [[SDImageCache sharedImageCache] clearDiskOnCompletion:^{
        NSLog(@"清理缓存");
    }];


2.对于账户中的账户信息,例如账户下的头像,名称,等最好是写一个用户类,使用单例的形式创建,使用kvo监听属性值的变化,并在属性变化之后更新本地存储的用户信息(最好不要存储敏感的信息,例如密码等),存储方式为对象归档,NSKeyedArchiver将oc对象进行序列化存储

存:其中的path是自定义的,例如:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Public/loginUserInfo"]

NSFileManager * fileManager = [NSFileManager defaultManager];
    NSError * error = nil;
    if (![fileManager fileExistsAtPath:path])
    {
        [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error];
        NSAssert(!error, @"创建路径错误");
    }
    NSString * fullPath = [path stringByAppendingPathComponent:path.lastPathComponent];
    [NSKeyedArchiver archiveRootObject:self.userInfoDict toFile:fullPath];

取:其中的path,就是上面存储时的路径.NSKeyedUnarchiver将存储的oc对象进行反序列化拿取.

NSFileManager * fileManager = [NSFileManager defaultManager];
        if ([fileManager fileExistsAtPath:path])
        {
            NSString * fullPath = [path stringByAppendingPathComponent:path.lastPathComponent];
            NSDictionary * dicget = [NSKeyedUnarchiver unarchiveObjectWithFile:fullPath];

}

删:

 NSFileManager * fileManager = [NSFileManager defaultManager];
    BOOL fileExists = [fileManager fileExistsAtPath:path];
    if (fileExists)
    {
        NSError *err;
        [fileManager removeItemAtPath:path error:&err];
    }


3.使用文件形式的存储

存:指定相应的文件存储路径.具体的方法为:其中fileName为自定义的子路径,可以用文件的名字命名(这里是存储的NSData,存储其他类型的数据也是可以的,比如NSArray)

 NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * path = [paths objectAtIndex:0];
    NSString * json_path = [path stringByAppendingPathComponent:fileName];
    //写入本地
    block([data writeToFile:json_path atomically:YES]);


取:其中的filePath为上面存储的文件的路径.当拿到data之后,我们要转为我们能操作的简单数据结构,这个就和存储时的数据结构一样就可以了.(这里用的数组)

 NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * path = [paths objectAtIndex:0];
    NSString * json_path = [path stringByAppendingPathComponent:filePath];
    NSData * data = [NSData dataWithContentsOfFile:json_path];
    if (!data)
    {
        NSArray * array;
        return array;
    }
    NSError * error = nil;
    NSArray * array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
    NSAssert(!error, @"读取数据失败");

删:其中fileName就是存储时的子路径

NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * path = [paths objectAtIndex:0];
    NSString * json_path = [path stringByAppendingPathComponent:fileName];
    NSFileManager * fileManager = [NSFileManager defaultManager];
    BOOL fileExists = [fileManager fileExistsAtPath:json_path];
    if (fileExists)
    {
        NSError *err;
        [fileManager removeItemAtPath:json_path error:&err];
    }

4.使用NSDefaults,这个就不在这多说了,使用也简单,存储的时候别忘记执行保存方法.


下面简答的介绍一下APP的沙盒组成,做本地存储的时候,归档数据存储位置为NSDocumentDirectory,使用data写入的位置也是NSDocumentDirectory,

Documents:保存应用运行时生成的需要持久化的数据,iTunes同步设备时会备份该目录。例如,游戏应用可以将游戏存档保存在该目录下。如果用户将缓存存放在这个文件夹下,会导致应用审核无法通过。
tmp:保存应用运行时所需要的临时数据,使用完毕后再将相应的文件从该目录删除。应用没有运行时,系统也可能会清除该目录下的文件。iTunes同步设备时不会备份该目录。
Library/Caches:保存应用运行时生成的需要持久化的数据,iTunes同步设备时不会备份该目录。一般存储体积大,不需要备份的非重要数据。
Library/Preference:保存应用的所有偏好设置,iOS的Settings(设置)应用会在该目录中查找应用的设置信息。iTunes同步设备时会备份该目录。


 //获取根目录  
NSString *homePath = NSHomeDirectory();  
NSLog(@"Home目录:%@",homePath);  

//获取Documents文件夹目录,第一个参数是说明获取Doucments文件夹目录,第二个参数说明是在当前应用沙盒中获取,所有应用沙盒目录组成一个数组结构的数据存放  
NSArray *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);  
NSString *documentsPath = [docPath objectAtIndex:0];  
NSLog(@"Documents目录:%@",documentsPath);  

     
//Library目录  
NSArray *libsPath = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);  
 NSString *libPath = [libsPath objectAtIndex:0];  
NSLog(@"Library目录:%@",libPath);  

//获取Cache目录  
  NSArray *cacPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);  
  NSString *cachePath = [cacPath objectAtIndex:0];  
  NSLog(@"Cache目录:%@",cachePath);  


 
//temp目录  
NSString *tempPath = NSTemporaryDirectory();  
NSLog(@"temp目录:%@",tempPath);  

原创粉丝点击