美文网首页
数据持久化(一)-----归档 读写 文件路径

数据持久化(一)-----归档 读写 文件路径

作者: UILabelkell | 来源:发表于2017-06-19 17:27 被阅读22次

    <pre>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]autorelease];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];

    /*HMTRootViewController * rootVC = [[HMTRootViewController alloc]init];
    self.window.rootViewController = rootVC;
    [rootVC release];*/
    
    // 1.获取沙盒文件的主路径
    NSLog(@"home = %@",NSHomeDirectory());
    
    // 2.获取Documents的路径(获取Library的路径类似)
    NSLog(@"documents = %@", [NSHomeDirectory() stringByAppendingString:@"/Documents"]);
    NSLog(@"documents = %@", [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]);
    NSLog(@"documents = %@",[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]);
    
    // 3.获取tmp的路径(单独的方法,与众不同)
    NSLog(@"tmp = %@",NSTemporaryDirectory());
    
    // 4.应用程序包.app-----只有读取的权利,没有修改的权利
    NSLog(@".app = %@",[[NSBundle mainBundle] bundlePath]);
    NSLog(@"resource = %@",[[NSBundle mainBundle]resourcePath]);
    NSLog(@".exec = %@",[[NSBundle mainBundle] executablePath]);
    
    //[self simpleOperationOfApp];
    [self complexOperationOfApp];
    [self complexArrayOperationOfApp];
    
    return YES;
    

    }

    pragma mark - 简单的数据文件write/read

    • (void)simpleOperationOfApp{

    pragma mark 字符串---txt

    // 1.获取存储文件的上一级路径
    NSString * documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    
    // 2.拼接一个完整的文件存储路径
    NSString * filePath = [documentsPath stringByAppendingPathComponent:@"text.txt"];
    
    // 3.write数据
    NSString * saveString = @"我叫胡明涛";
    [saveString writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    // 4.从文件中read
    NSString * readString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"%@",readString);
    

    pragma mark 数组---plist

    NSString * cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString * arrayFilePath = [cachesPath stringByAppendingPathComponent:@"names.plist"];
    NSArray * writeArray = @[@"吴凯",@"许珍珍",@"左友东"];
    [writeArray writeToFile:arrayFilePath atomically:YES];
    
    NSArray * readArray = [NSArray arrayWithContentsOfFile:arrayFilePath];
    NSLog(@"%@",readArray);
    

    pragma mark 字典---plist

    NSString * tmpPath = NSTemporaryDirectory();
    NSString * dicFilePath = [tmpPath stringByAppendingPathComponent:@"dic.plist"];
    NSDictionary * writeDic = @{@"name": @"HMT",@"sex":@"female"};
    [writeDic writeToFile:dicFilePath atomically:YES];
    
    NSDictionary * readDic = [NSDictionary dictionaryWithContentsOfFile:dicFilePath];
    NSLog(@"%@",readDic);
    
    // 修改数据
    [readDic setValue:@"humingtao" forKey:@"name"];
    [readDic writeToFile:dicFilePath atomically:YES];
    NSLog(@"%@",readDic);
    

    pragma mark NSData

    // 获取图片对象
    UIImage * writeImage = [UIImage imageNamed:@"OJ2NMBNXQ1G5_20121120051201760"];
    
    // 图片对象转变为NSData类型
    NSData * writeData = UIImagePNGRepresentation(writeImage);
    
    NSString * imageFilePath = [documentsPath stringByAppendingPathComponent:@"美女.png"];
    [writeData writeToFile:imageFilePath atomically:YES];
    
    NSData * readData = [NSData dataWithContentsOfFile:imageFilePath];
    // imageNamed------图片会存入缓存,下次加载很迅速,但是耗内存,图片一大就嗝屁了
    UIImage * readImage = [UIImage imageWithData:readData];
    // 从文件路径中找,调用一次就重新加载一次,只是显示图片,不加载到内存(后缀名不要加".")
    [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"美女" ofType:@"png"]];
    NSLog(@"%@",readImage);
    NSLog(@"%@",[UIImage imageWithContentsOfFile:imageFilePath]);
    

    }

    pragma mark - 单个--复杂的数据对象write/read-------NSCoding协议

    • (void)complexOperationOfApp{

      UIButton * archiver = [UIButton buttonWithType:UIButtonTypeSystem];
      archiver.frame = CGRectMake(20, 100, 100, 40);
      [archiver setTitle:@"归档(序列化)" forState:UIControlStateNormal];
      [archiver addTarget:self action:@selector(onClickArchiverButton:) forControlEvents:UIControlEventTouchUpInside];
      [self.window addSubview:archiver];

      UIButton * unArchiver = [UIButton buttonWithType:UIButtonTypeSystem];
      unArchiver.frame = CGRectMake(160, 100, 120, 40);
      [unArchiver setTitle:@"反归档(反序列化)" forState:UIControlStateNormal];
      [unArchiver addTarget:self action:@selector(onClickUnArchiverButton:) forControlEvents:UIControlEventTouchUpInside];
      [self.window addSubview:unArchiver];
      }

    pragma mark 对复杂的数据对象进行写入操作.原理:复杂的数据对象序列化为NSData,将NSData写入文件,实现数据持久化

    • (void)onClickArchiverButton:(UIButton *)button{

      /**

      • 1.自定义复杂的数据类型,例如ABPerson
      • (1)ABPerson必须实现NSCoding协议的方法
      • (2)ABPerson中的实例变量或属性,也必须实现NSCoding协议的方法
      • (3)ABPerson中的基本数据类型没有过多限制
      • 2.创建一个序列化工具对象
      • 3.先找路径
      • 4.对复杂的数据类型对象进行序列化
      • 5.结束 finishEncoding
      • 6.NSData写入
        */
        HMTABPerson * person = [[HMTABPerson alloc]init];
        person.name = @"HMT";
        person.age = 25;

      NSMutableData * archiverData = [NSMutableData data];
      NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:archiverData];

      [archiver encodeObject:person forKey:@"PersonKey"];

      [archiver finishEncoding];

      NSString * documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
      NSString * filePath = [documents stringByAppendingPathComponent:@"person.data"];

      [archiverData writeToFile:filePath atomically:YES];

      [person release];
      [archiver release];

    }

    pragma mark 从文件中读取数据来实例化复杂对象数据操作

    • (void)onClickUnArchiverButton:(UIButton *)button{

      /**

      • 1.先找路径
      • 2.NSData读出
      • 3.创建一个反序列化工具
      • 4.反序列化
      • 5.结束 finishDecoding
      • 6.操作对象了
        */
        NSString * documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
        NSString * filePath = [documents stringByAppendingPathComponent:@"person.data"];

      NSData * unarchiverData = [NSData dataWithContentsOfFile:filePath];

      NSKeyedUnarchiver * unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:unarchiverData];

      HMTABPerson * person = [unarchiver decodeObjectForKey:@"PersonKey"];

      [unarchiver finishDecoding];

      NSLog(@"%@",person.name);

      [unarchiver release];

    }

    pragma mark - 数组--复杂的数据对象write/read-------NSCoding协议

    • (void)complexArrayOperationOfApp{

      UIButton * archiver = [UIButton buttonWithType:UIButtonTypeSystem];
      archiver.frame = CGRectMake(20, 200, 100, 40);
      [archiver setTitle:@"归档(序列化)" forState:UIControlStateNormal];
      [archiver addTarget:self action:@selector(onClickArchiverArrayButton) forControlEvents:UIControlEventTouchUpInside];
      [self.window addSubview:archiver];

      UIButton * unArchiver = [UIButton buttonWithType:UIButtonTypeSystem];
      unArchiver.frame = CGRectMake(160, 200, 120, 40);
      [unArchiver setTitle:@"反归档(反序列化)" forState:UIControlStateNormal];
      [unArchiver addTarget:self action:@selector(onClickUnArchiverArrayButton) forControlEvents:UIControlEventTouchUpInside];
      [self.window addSubview:unArchiver];

    }

    pragma mark 写入

    • (void)onClickArchiverArrayButton{

      NSMutableData * archiverData = [NSMutableData data];
      NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:archiverData];

      HMTABPerson * person1 = [[HMTABPerson alloc]init];
      person1.name = @"陈凤长";
      person1.age = 24;

      HMTABPerson * person2 = [[HMTABPerson alloc]init];
      person2.name = @"胡明涛";
      person2.age = 24;

      NSArray * personArray = @[person1,person2];

      [archiver encodeObject:personArray forKey:@"PersonArrayKey"];

      [archiver finishEncoding];

      NSString * tmpPath = NSTemporaryDirectory();
      NSString * filePath = [tmpPath stringByAppendingPathComponent:@"personArray.plist"];

      [archiverData writeToFile:filePath atomically:YES];

      [person1 release];
      [person2 release];
      [archiver release];

    }

    pragma mark 读取

    • (void)onClickUnArchiverArrayButton{

      NSString * tmpPath = NSTemporaryDirectory();
      NSString * filePath = [tmpPath stringByAppendingPathComponent:@"personArray.plist"];

      NSData * unarchiverData = [NSData dataWithContentsOfFile:filePath];

      NSKeyedUnarchiver * unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:unarchiverData];

      NSArray * personArray = [unarchiver decodeObjectForKey:@"PersonArrayKey"];

      [unarchiver finishDecoding];

      HMTABPerson * person1 = [personArray objectAtIndex:0];
      HMTABPerson * person2 = [personArray objectAtIndex:1];

      NSLog(@"%@ %@",person1.name,person2.name);

      [unarchiver release];

    }
    HMTABPerson.h

    import <Foundation/Foundation.h>

    @interface HMTABPerson : NSObject <NSCoding>

    @property (nonatomic,assign)int age;
    @property (nonatomic,copy) NSString * name;

    @end
    HMTABPerson.m

    import "HMTABPerson.h"

    @implementation HMTABPerson

    • (void)dealloc{

      [_name release];
      [super dealloc];
      }

    // 序列化,编码

    • (void)encodeWithCoder:(NSCoder *)aCoder{

      [aCoder encodeObject:_name forKey:@"NameKey"];
      [aCoder encodeInt:_age forKey:@"AgeKey"];

    }

    // 反序列化,解码

    • (id)initWithCoder:(NSCoder *)aDecoder{

      if (self = [super init]) {

        self.name = [aDecoder decodeObjectForKey:@"NameKey"];
        self.age  = [aDecoder decodeIntForKey:@"AgeKey"];
      

      }

      return self;
      }

    @end</pre>

    相关文章

      网友评论

          本文标题:数据持久化(一)-----归档 读写 文件路径

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