iOS编程------初级数据持久化/沙盒机制/NSFileManager/简单对象写入文件/复杂对象写入文件

//
//  AppDelegate.h
//  UI18_sandBox_simpleObjectWriteToFile
//
//  Created by l on 15/9/24.
//  Copyright (c) 2015年 . All rights reserved.
//

#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;


@end







//
//  AppDelegate.m
//  UI18_sandBox_simpleObjectWriteToFile
//
//  Created by l on 15/9/24.
//  Copyright (c) 2015年 . All rights reserved.
//

#import "AppDelegate.h"
#import "Person.h"
@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    //UI18  沙盒机制 , 简单对象写入文件, 复杂对象写入文件, NSFileManager文件管理类

    //一,沙盒
    //沙盒根路径
    NSLog(@"%@", NSHomeDirectory());

    //沙盒路径下面有三个文件夹
    //Documents 文档,存放需要备份的内容,如果有iCloud服务,上传到云端的就是Documents里面的内容,注意:Documents里面不能存放大数据(音频,视频等)否则上传会被拒.

    //Library 资源库
    //Cache 缓存 缓存中主要存放音频,视频,图片等,是专门用来存放用户缓存的文件夹.
    //Preference 偏好设置,用来存放相关的偏好设置,我们可以通过NSUserDefault 存放用户相关设置.

    //tmp 临时文件
    //tmp 临时文件夹主要用来存储下一次程序启动不需要的数据,当本次程序结束时,会把临时文件夹里面的数据清除.
    //也用来存储下载没有完全的文件,下载完成后移动到Cache里面.

    //------------------//

    //获取沙盒路径的三种方式
    //1.使用系统提供的函数直接获得home和tmp的沙盒路径.
    //home 根路径
    NSString *homePath = NSHomeDirectory();
    NSLog(@"%@", homePath);

    //tmp 路径
    NSString *tmpPath = NSTemporaryDirectory();
    NSLog(@"%@", tmpPath);

    //2.拼接字符串获取
    //拼接string 一定要加上层级"/"
    NSString *preferencePath = [NSHomeDirectory() stringByAppendingString:@"/Library/perferences"];
    NSLog(@"%@", preferencePath);

    //拼接路径 当前级别不用加"/"
    NSString *cachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Cache"];
    NSLog(@"%@", cachePath);


    //3.通过函数查找路径 Documents Cache Library tmp
    NSString *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSLog(@"%@", documents);

    NSString *library = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSLog(@"%@", library);

    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSLog(@"%@", caches);


    //获取主包路径
    NSBundle *bundle = [NSBundle mainBundle];
    NSLog(@"%@", bundle);
    //获取包中文件路径
    NSString *filePath = [bundle pathForResource:@"" ofType:@""];
    NSLog(@"%@", filePath);


    //----------------//

    //二. 简单对象写入文件
    //foundation 中的简单对象有以下四种
    //string
    //array
    //dictionary
    //data
    //只有以上四种对象可以调用系统提供的方法 writeToFile 直接写入文件中.

    //1.字符串写入文件
    //(1)
    NSString *string = @"同志们好! 首长好!";
    //(2)文件路径 ~string;
    NSString *stringPath = [NSHomeDirectory() stringByAppendingPathComponent:@"string.txt"];
    //(3)写入文件
    [string writeToFile:stringPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    //(4)读取
    NSLog(@"%@", [NSString stringWithContentsOfFile:stringPath encoding:NSUTF8StringEncoding error:nil]);

    //2.数组写入文件
    NSArray *array = @[@"星期四", @"星期五"];
    NSString *arrayPath = [NSHomeDirectory() stringByAppendingPathComponent:@"array.plist"];
    [array writeToFile:arrayPath atomically:YES];
    NSLog(@"%@", [NSArray arrayWithContentsOfFile:arrayPath]);

    //3.字典写入文件
    NSDictionary *dic = @{@"name" : @"houlianyuan"};
    NSString *dicPath = [NSHomeDirectory() stringByAppendingPathComponent:@"dic.json"];
    [dic writeToFile:dicPath atomically:YES];
    NSLog(@"%@", [NSDictionary dictionaryWithContentsOfFile:dicPath]);

    //4.data 文件写入
    UIImage *image = [UIImage imageNamed:@"image1.jpg"];
    NSData *data = UIImagePNGRepresentation(image);//图片转换为data数据类型
    NSString *dataPath = [NSHomeDirectory() stringByAppendingPathComponent:@"image1.dat"];
    [data writeToFile:dataPath atomically:YES];
    //读取
    UIImage *image2 = [UIImage imageWithData:[NSData dataWithContentsOfFile:dataPath]];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:(CGRectMake(37, 100, 300, 300))];
    imageView.image = image2;
    [self.window.rootViewController.view addSubview:imageView];

    //-----------------//

   //归档  反归档   复杂对象写入文件
    //复杂对象没有办法直接写入文件,只有通过转化为data类型的数据,通过writeToFile方法,写入文件
    //复杂对象 转化为data的过程是一个编码的过程,使用NSKeyedArchiver,称为复杂对象的归档                            Archiver --> 归档器
    //        NSKeyedArchiver
    //model ------------------------------> mutableData

    //由data转化为复杂对象的过程是一个解码的过程,使用NSKeyedUnarchiver,称为反归档.
    //model <-------------------------------mutableData
    //         NSKeyedUnarchiver

    //复杂对象是foundation框架中不存在的对象,没有writeToFile方法
    //复杂对象想要被归档和反归档,必须遵守NSCoding协议,实现编码和解码方法.


    //创建复杂对象 person1
    Person *person1 = [[Person alloc] init];
    person1.name = @"王右";
    person1.age = 16;
    person1.image = [UIImage imageNamed:@"image1.jpg"];

    //归档步骤
    //1.创建mutableData
    NSMutableData *mutableData = [NSMutableData data];

    //2.创建归档对象,初始化时指定对应的mutableData
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:mutableData];
    [archiver encodeObject:person1 forKey:@"person1"];
    //结束编码
    [archiver finishEncoding];

    //把data数据写入到文件中
    NSString *archiverPath = [NSHomeDirectory() stringByAppendingPathComponent:@"archiver.dat"];

    [mutableData writeToFile:archiverPath atomically:YES];


    //反归档 过程
    //1.data 对象
    NSData *data2 = [NSData dataWithContentsOfFile:archiverPath];

    //2.创建反归档对象 NSKeyedUnarchiver
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data2];

    //进行解码,反归档
      Person *person2 = [unarchiver decodeObjectForKey:@"person1"];

    //结束
    [unarchiver finishDecoding];

    NSLog(@"%@ %ld", person2.name, person2.age);

    UIImageView *imageView2 = [[UIImageView alloc] initWithFrame:(CGRectMake(0, 350, 300, 300))];
    imageView2.image = person2.image;
    [self.window.rootViewController.view addSubview:imageView2];

    //---------------------//


    //四. 文件管理类
    //文件管理类 是 对文件或者文件夹 执行相关的操作,比如:创建,删除,移动,复制,重命名,以及某个路径下是否存在文件等等.

    //1.文件管理类
    //单例
    NSFileManager *fileManager = [NSFileManager defaultManager];

    //2.执行相关操作

    //(1)创建文件
    //1.文件路径  一定要包含文件名,才是该文件的完整路径
    // home/girlDic
    NSString *grilPath = [NSHomeDirectory() stringByAppendingPathComponent:@"/a/b/grilDic"];

    //withIntermediateDirectories: 是否创建中间文件路径
    [fileManager createDirectoryAtPath:grilPath withIntermediateDirectories:YES attributes:nil error:nil];

    //(2) 删除文件
//    [fileManager removeItemAtPath:girlPath error:nil];

    //(3)移动文件
    //源路径
    NSString *srcPath = grilPath;
    //目标路径
    NSString *desPath = [NSHomeDirectory() stringByAppendingPathComponent:@"grilDic"];
    //移动
    [fileManager moveItemAtPath:srcPath toPath:desPath error:nil];


    //(3.5)重命名,重命名是移动中的一种
    //目标路径和源路径级别没有发生变化,只是,文件名发生了变化
    //home/grilDic -> home/boyDic
    NSString *srcPath2 = desPath;
    NSString *desPath2 = [NSHomeDirectory() stringByAppendingPathComponent:@"boyDic"];
    [fileManager moveItemAtPath:srcPath2 toPath:desPath2 error:nil];


    //(4)拷贝
    //拷贝源路径
    //home/boyDic -> tmp/boyDic
    NSString *srcPath3 = desPath2;
    //目标路径
    NSString *desPath3 = [NSTemporaryDirectory() stringByAppendingPathComponent:@"boyDic"];
    [fileManager copyItemAtPath:srcPath3 toPath:desPath3 error:nil];


    //(5)是否存在
    //缓存文件夹路径
    NSString *cachePath2 = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];

    //图片缓存文件夹路径
    // home/Library/Caches/imageCache
    NSString *imageCache = [cachePath2 stringByAppendingPathComponent:@"imageCache"];

    //如果Cache缓存图片文件夹不存在,那么我们就创建一个缓存图片文件夹
    if (![fileManager fileExistsAtPath:imageCache]) {

        //创建文件夹
        [fileManager createDirectoryAtPath:imageCache withIntermediateDirectories:YES attributes:nil error:nil];

    }


    // Override point for customization after application launch.

    return YES;
}

@end






///






//
//  Person.h
//  UI18_sandBox_simpleObjectWriteToFile
//
//  Created by l on 15/9/24.
//  Copyright (c) 2015年 . All rights reserved.
//

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface Person : NSObject<NSCoding>

@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) NSInteger age;
@property (nonatomic, strong) UIImage *image;

@end







//
//  Person.m
//  UI18_sandBox_simpleObjectWriteToFile
//
//  Created by l on 15/9/24.
//  Copyright (c) 2015年 . All rights reserved.
//
#define KName @"name"
#define KAge @"age"
#define KImage @"image"

#import "Person.h"

@implementation Person

//编码方法
//当对象被归档的时候执行
- (void)encodeWithCoder:(NSCoder *)aCoder{

    //当被编码的对象为string,dic,array的时候
    [aCoder encodeObject:self.name forKey:KName];

    [aCoder encodeInteger:self.age forKey:KAge];

    //对data编码使用dataObject,不用添加标识符
    [aCoder encodeDataObject:UIImagePNGRepresentation(self.image)];

}

//解码
//解码的过程是由data重新生成model的过程,因此是初始化方法.
//解码 反归档的时候触发,生成一个新的model对象
- (id)initWithCoder:(NSCoder *)aDecoder{

    self = [super init];

    if (self) {

        self.name = [aDecoder decodeObjectForKey:KName];
        self.age = [aDecoder decodeIntegerForKey:KAge];
        //imageWithData: 创建图片
        self.image = [UIImage imageWithData:[aDecoder decodeDataObject]];

    }
    return self;
}



@end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值