简单对象写入文件

87 篇文章 0 订阅

#pragma mark 写入文件 

    //简单对象写入文件---------------->字符串、数组、字典、图片(才怪,是把图片转换成的NSData对象)

    

    //1.字符串

  

    

    NSString *incantation = @"yi hu shi ";

    

    

    NSString *homePath = NSHomeDirectory();

    

    homePath = [homePath stringByAppendingString:@"/hh.txt"];

    

    //NO:不安全,会中断。

    //AllowLossy允许丢失碎片。

    //ExternalRepresentation按字节转换,一个字节也不能丢失。

    [incantation writeToFile:homePath atomically:YES encoding:NSStringEncodingConversionExternalRepresentation error:nil];

    

    NSLog(@"%@",homePath);

    

    

    //从文件获取字符串

    NSString *result = [NSString stringWithContentsOfFile:homePath encoding:NSStringEncodingConversionExternalRepresentation error:nil];

    

    NSLog(@"%@",result);

    

    

 

    

    //2、数组写入文件

 

    NSArray *array = @[@"you",@"are",@"you"];

    

    

    NSString *path = NSHomeDirectory();

    

    path = [path stringByAppendingString:@"hitu"];

    

    //写入

    [array writeToFile:path atomically:YES];

    

    NSLog(@"%@",path);

    

    //读取

    NSArray *resultArray = [NSArray arrayWithContentsOfFile:path];

    

    NSLog(@"%@",resultArray);

 

    

    

    //3、字典写入文件

 

    NSDictionary *dictionary = @{

                                 @"yiyi":@"huhu",

                                 @"yoyo":@"kiki"

                                 };

    

    

    NSString *path = NSHomeDirectory();

    

    path = [path stringByAppendingString:@"/oppo.txt"];

    

    //写入

    [dictionary writeToFile:path atomically:YES];

    

    NSLog(@"%@",path);

    

    //读取

    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];

    

    NSLog(@"%@",dict);

  

    

    //4、图片是以NSData写入文件

   

    UIImage *image = [UIImage imageNamed:@"background.png"];

    

    //0-1之间的,1是原封不动的大小

    NSData *data = UIImageJPEGRepresentation(image, 0.5);

    

    NSString *path = NSHomeDirectory();

    

    path = [path stringByAppendingString:@"/image"];

    

    

    //写入

    [data writeToFile:path atomically:YES];

    

    NSLog(@"%@",path);

    

    //读取

    NSData *resultData = [NSData dataWithContentsOfFile:path];

    

    UIImage *resultImage = [UIImage imageWithData:resultData];

    

    [_imageView setImage:resultImage];

    

   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值