• IOS数据持久化之归档NSKeyedArchiver, NSUserDefaults,writeToFile


    
    
     
        //2.文件读写
        //支持:NSString, NSArray , NSDictionay, NSData
         //注:集合(NSArray, NSDictionay)中得元素也必须是这四种类型, 才能够进行文件读写
         
         //string文件读写
        NSString *string = @"假如给我有索纳塔";
       
        //Document
        NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
        //指定文件路径 aaa.txt
        NSString *filePath = [docPath stringByAppendingPathComponent:@"aaa.txt"];
        NSLog(@"**%@", filePath);
        //写入文件
        //参数1:文件路径, 如果文件路径下没有此文件, 系统会自动创建一个文件.
        //参数2:是否使用辅助文件
        //参数3:编码格式
        //参数4:错误
        NSError *error = nil;
        BOOL result = [string writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
        if (result) {
            NSLog(@"写入成功");
        } else {
        
            NSLog(@"写入错误");
        }
        if (error) {
            NSLog(@"出现错误");
        }
        
        //取值操作,
        NSError  *error1 = nil;
        NSString *contenSring = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error1];
        if (error1) {
            NSLog(@"error:%@", error1);
        } else {
            NSLog(@"文件内容%@", contenSring);
        }
        [contenSring release];
        
        
        
        
        //NSArray的文件读写
        
        NSArray *array = @[@"123", @"abc", @"apm"];
        //写入操作, 格式XML
        //Library, test.txt
        //library路径
        NSString *libraryPath1 = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];
        //文件路径
        NSString *textPath = [libraryPath1 stringByAppendingPathComponent:@"text.txt"];
        NSLog(@"%@", textPath);
        //写入
        BOOL result4 = [array writeToFile:textPath atomically:YES];
        //判断是否写入成功
        if (result4) {
            NSLog(@"写入成功");
        } else {
            NSLog(@"写入失败");
        }
        
        //取值操作
       
        NSArray *bbb = [[NSArray alloc] initWithContentsOfFile:textPath];
        NSLog(@"%@", bbb);
        [bbb release];
        
        
        
        
        
        //NSDictionary, 格式:XMl
        NSDictionary *dic = @{@"a": @"aaa", @"1": @"111", @"*" :@"**"};
        //Caches, dic.txt
        //Caches文件路径
        NSString *cachesPath1 = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)firstObject];
        //dic.txt路径
        NSString *dicPath = [cachesPath1 stringByAppendingPathComponent:@"dic.txt"];
        NSLog(@"%@", dicPath);
        //写入
        BOOL result3 = [dic writeToFile:dicPath atomically:YES];
        //判断写入是否成功
        if (result3) {
            NSLog(@"写入成功");
        } else {
            NSLog(@"写入shib");
        }
        //取值操作
        NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:dicPath];
        NSLog(@"%@", dict);
        [dict release];
        
        
        
        //NSData NSString *tmpPath = NSTemporaryDirectory();
        NSString *string2 = @"132456789";
        //字符串转data
         NSData *data = [string2 dataUsingEncoding:NSUTF8StringEncoding];
        //tmp路径
        //tmp data.txt
        NSString *tmpPath1 = NSTemporaryDirectory();
        //data.txt路径
         NSString *dataPath = [tmpPath1 stringByAppendingPathComponent:@"data.txt"];
        //写入
        BOOL result1 = [data writeToFile:dataPath atomically:YES];
        //判断是否写入成功
        if (result1) {
            NSLog(@"写入成功");
        } else {
            NSLog(@"写入失败");
        }
        
        //取值
        NSData *datat = [[NSData alloc] initWithContentsOfFile:dataPath];
        NSString *dataSting = [[NSString alloc] initWithData:datat encoding:NSUTF8StringEncoding];
         [datat release];
        NSLog(@"%@", dataSting);
        [dataSting release];
        
    
    
     1     //3.归档 / 反归档
     2     //归档的实质:把其他类型数据(比如:Person),先转化成NSData, 再写入文件
     3     //能进行归档的对象, 必须遵守<NSCoding>
     4     
     5     //归档
     6     Person *person = [[[Person alloc] init] autorelease];
     7     person.name = @"辉哥";
     8     person.age = @"18";
     9     person.gender = @"";
    10     //NSLog(@"%@", person);
    11     
    12     
    13     //可变data
    14     NSMutableData *mData = [[NSMutableData alloc] initWithCapacity:0];
    15     
    16     //NSKeyedArchiver, 压缩工具, 继承于NSCoder,主要用于编码
    17     NSKeyedArchiver *archiver= [[NSKeyedArchiver alloc] initForWritingWithMutableData:mData];
    18     //把Person对象压到Data中
    19     [archiver encodeObject:person forKey:@"girlFriend"];
    20     //完成压缩
    21     [archiver finishEncoding];
    22     [archiver release];
    23     NSLog(@"%@", mData);
    24     
    25     //主目录中, person.txt
    26       NSString *homePatha = NSHomeDirectory();
    27       NSString *mDataPath = [homePatha stringByAppendingPathComponent:@"person.txt"];
    28     NSLog(@"%@", mDataPath);
    29     BOOL result = [mData writeToFile:mDataPath atomically:YES];
    30     if (result) {
    31         NSLog(@"写入成功");
    32     } else {
    33         NSLog(@"写入失败");
    34     }
    35     [mData release];
    36 
    37     //反归档
    38     NSData *contentData = [[NSData alloc] initWithContentsOfFile:mDataPath];
    39     //NSKeyedUnarchiver解压工具, 继承于NSCoder
    40     NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:contentData];
    41     [contentData release];
    42     //通过key找到person
    43    Person *contentPerson = [unarchiver decodeObjectForKey:@"girlFriend"];
    44     NSLog(@"gd%@", contentPerson);
    45     [unarchiver release];
    46     
      1   
      2     //数据持久化:数据永久的保存
      3     //数据持久化的实质:把数据写入文件, 再把文件存到硬盘
      4     //IOS沙盒机制:IOS系统为每个app生成一个文件夹(沙盒), 这个文件夹只允许当前的APP访问
      5     //沙盒的主目录
      6     //沙盒主目录的文件夹名字由 十六进制数 和 - 组成, 保证沙盒安全性
      7     //NSHomeDirectory()
      8     NSString *homePath = NSHomeDirectory();
      9     NSLog(@"%@", homePath);
     10     
     11     //Documents文件
     12     //存放着一些比较重要的用户信息, 比如游戏的存档
     13     //Documents中得文件会被备份 或者 存入iCloud 中, 所以存到documents中得文件不能过大, 如果过大, 会在应用审核过程中遭到拒审
     14     //参数1:文件夹名称
     15     //参数2:搜素域 优先级user>local>network>system
     16     //参数3:相对路径或者绝对路径, yes 是绝对, no是相对
     17     //因为相同文件名的文件可能有多个, 所以返回的是一个数组
     18     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
     19     //NSLog(@"%@", paths);
     20     
     21     NSString *docmentsPath = [paths firstObject];
     22     //NSLog(@"%@", docmentsPath);
     23     
     24     //Library,资源库 存放一些不太重要, 相对比较大得文件
     25     NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];
     26     //NSLog(@"libraryPath:%@", libraryPath);
     27     //Library/Caches, 缓存, 网页缓存, 图片缓存, 应用中得"清理缓存"功能, 就是清理这个文件夹下得内容
     28     NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
     29     //NSLog(@"%@", cachesPath);
     30     //LanunchImages, 由LaunchScreen.xib生成的启动图片
     31     
     32     
     33     //Library/Preferences, 偏好设置, 存放用户对这个应用的设置或配置
     34     //注:路径找不到,通过NSUserDefaults访问
     35     
     36     
     37     //tmp, 临时文件, 存放下载的压缩包, 解压过后删除
     38     NSString *tmpPath = NSTemporaryDirectory();
     39     NSLog(@"%@", tmpPath);
     40     
     41     //  *.app, 包,用右键,显示包内容, 查看里面存放的文件
     42     //IOS8.0以后, *.app单独存放到一个文件内
     43     //  *.app中这个文件,只能够访问,不能够修改(写入)
     44     NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
     45     NSLog(@"***%@", bundlePath);
     46     
     47     
     48     //NSFileManager文件管理工具, 主要用于添加, 移动, 修改, 拷贝文件, 继承于NSObject
     49     //文件管理工具是个单例
     50     NSFileManager *fm = [NSFileManager defaultManager];
     51     //文件路径
     52     NSString *hPath = [[fm URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject];
     53     NSLog(@"hPath:%@", hPath);
     54     
     55     //创建文件夹,
     56     //在主目录中创建images文件夹
     57     NSString *mainPath = NSHomeDirectory();
     58     NSString *directoryPath = [mainPath stringByAppendingPathComponent:@"images"];
     59     NSLog(@"%@", directoryPath);
     60     
     61     NSError *error = nil;
     62     //attributes设置文件夹的属性,读写,隐藏等等
     63     //NSDictionary *attributes = @{NSFileAppendOnly: @YES};
     64     BOOL result = [fm createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:nil error:&error];
     65     if (result) {
     66         NSLog(@"创建成功");
     67     } else {
     68     
     69         NSLog(@"创建失败");
     70     }
     71     
     72     //创建文件
     73     //在Images文件夹中创建image.png
     74     NSString *imagePath = [directoryPath stringByAppendingPathComponent:@"image.png"];
     75     NSLog(@"%@", imagePath);
     76     
     77     //找图片
     78     NSString *meinvPath = [[NSBundle mainBundle] pathForResource:@"美女7" ofType:@"png"];
     79     NSData *imageData = [NSData dataWithContentsOfFile:meinvPath];
     80     
     81     //创建图片
     82     BOOL result2 = [fm createFileAtPath:imagePath contents:imageData attributes:nil];
     83     if (result2) {
     84         NSLog(@"创建成功");
     85     } else {
     86         NSLog(@"创建失败");
     87     }
     88     
     89     //判断文件是否存在
     90     if ([fm fileExistsAtPath:imagePath]) {
     91         NSLog(@"存在");
     92         //删除
     93         NSError *error = nil;
     94        BOOL result = [fm removeItemAtPath:imagePath error:&error];
     95         if (result) {
     96             NSLog(@"删除成功");
     97         } else {
     98             NSLog(@"删除失败%@", error);
     99         }
    100     }
    101     
    102     NSString *path = NSHomeDirectory();
    103     NSString *filePath = [path stringByAppendingPathComponent:@"aaa.txt"];
    104     NSLog(@"1*%@", filePath);
    105     NSString *filePath1 =[path stringByAppendingString:@".aaa.txt"];
    106     NSLog(@"2*%@", filePath1);
    107     NSString *filePath2 = [path stringByAppendingFormat:@"/baa.txt"];
    108     NSLog(@"3*%@", filePath2);
    109     NSString *filePath3 = [path stringByAppendingPathExtension:@"caaa.txt"];
    110     NSLog(@"4*%@", filePath3);
    111     
    112     
    113     
    114     
    115     
    116 
    117     //数据持久化的方式
    118    //1. NSUserDefaults, 继承于NSObject, 单例设计模式, 内部存值用的KVC
    119     NSInteger money = 100000;
    120     money -= 99999;
    121     
    122     //存数据, 存放到PreFerences文件夹内的*.plist文件中, 以字典的形式存储
    123     NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    124     
    125     [userDefaults setInteger:1 forKey:@"myMoney"];
    126     //同步操作, 让存入的数据写入文件
    127     [userDefaults synchronize];
    128     
    129     
    130     //取数据, key和存数据的key保持一致
    131     NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    132     NSInteger myMoney = [user integerForKey:@"myMoney"];
    133     NSLog(@"%ld", myMoney);
    134     
    135     
    136     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    137     NSInteger mmoney = [defaults integerForKey:@"myLifeMoney"];
    138     if (mmoney <= 10) {
    139         NSLog(@"不能花了");
    140     } else {
    141         NSLog(@"花了10, 吃了俩");
    142         mmoney -= 10;
    143         [defaults setInteger:mmoney forKey:@"myLifeMoney"];
    144         [defaults synchronize];
    145     }
    146  
    147     
    148     //NSUserDefaults, 支持的数据类型:array, dictionary, string, data, date, number, bool
    149     //NSUserDefaults, 一般存一些数值, 不存大量的数据
    150     //是不是第一次启动
    151     NSUserDefaults *userDefault1 = [NSUserDefaults standardUserDefaults];
    152     BOOL isFirst = [userDefault1 boolForKey:@"isFirst"];
    153     if (isFirst == NO) {
    154         NSLog(@"第一次启动");
    155         [userDefault1 setBool:YES forKey:@"isFirst"];
    156     } else {
    157         NSLog(@"不是第一次启动");
    158     }

    Person.h 中实现NSCoding协议   

    #import <Foundation/Foundation.h>
    
    @interface Person : NSObject<NSCoding>
    
    @property (nonatomic , retain) NSString *name, *age, *gender;
    
    @end

    Person.m 中实现的方法

     1 #import "Person.h"
     2 
     3 @implementation Person
     4 - (void)dealloc
     5 {
     6     [_age release];
     7     [_name release];
     8     [_gender release];
     9     [super dealloc];
    10     
    11 }
    12 
    13 - (NSString *)description
    14 {
    15     return [NSString stringWithFormat:@"name:%@, age:%@, gender:%@", _name, _age, _gender];
    16 }
    17 
    18 #pragma mark - NSCoding
    19 - (void)encodeWithCoder:(NSCoder *)aCoder {
    20     //编码
    21     [aCoder encodeObject:self.name forKey:@"NAME"];
    22     [aCoder encodeObject:self.age forKey:@"AGE"];
    23     [aCoder encodeObject:self.gender forKey:@"GENDER"];
    24 }
    25 - (id)initWithCoder:(NSCoder *)aDecoder {
    26     self = [super init];
    27     if (self) {
    28         //解码
    29         self.name = [aDecoder decodeObjectForKey:@"NAME"];
    30         self.age = [aDecoder decodeObjectForKey:@"AGE"];
    31         self.gender = [aDecoder decodeObjectForKey:@"GENDER"];
    32     }
    33     return self;
    34 }
    35 
    36 
    37 @end

    @interface Person : NSObject<NSCoding>


     
  • 相关阅读:
    Mayi_Maven安装与配置Myeclipse、Idea
    MY_Selenium登录126邮箱,定位不到账号输入框解决办法
    MY_使用selenium自动登录126/163邮箱并发送邮件
    2、TestNG+Maven+IDEA环境搭建
    1、Maven安装教程详解
    git常用命令
    LUA_linux的安装
    vsftp虚拟用户配置
    apache日志切割
    NTP Reply Flood Attack (NTP反射型DDos攻击)
  • 原文地址:https://www.cnblogs.com/zhaoweizheng/p/4562134.html
Copyright © 2020-2023  润新知