OC-沙箱&归档

来源:互联网 发布:计算机的软件组成 编辑:程序博客网 时间:2024/04/30 07:34

沙箱:

Documents:最长打交道的文件夹,保存长期有用数据 iTunes会备份此文件夹
Library/Caches: 缓存文件夹 装缓存数据 iTunes不会备份
Library/Preferences:偏好设置文件夹 保存用户偏好设置数据 iTunes会备份
tmp:临时文件夹 装临时文件 此文件夹数据会不定时清除 iTunes不会备份

NSLog(@"沙箱的根目录:%@",NSHomeDirectory());    NSString *documentPath1 = [NSHomeDirectory() stringByAppendingString:@"/Documents"];    documentPath1 = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];    NSString *documentPath2 = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];    NSLog(@"%@--%@",documentPath1,documentPath2);    //得到临时文件夹    NSString *tmpPath = NSTemporaryDirectory();    NSLog(@"临时文件夹:%@",tmpPath);    //得到缓存文件夹    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)firstObject];    NSLog(@"缓存文件夹:%@",cachePath);    NSString *filePath = [documentPath1 stringByAppendingPathComponent:@"names.plist"];    NSArray *names = @[@"刘德华",@"张学友",@"郭富城",@"赵四"];    [names writeToFile:filePath atomically:YES];

用户偏好设置Library/Prefrence:

NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];    //保存数据    [ud setInteger:18 forKey:@"age"];    //同步    [ud synchronize];    //获取数据    NSInteger age = [ud integerForKey:@"age"];

归档:把对象转成Data的一种方式

只有实现了NSCoding协议的对象 才能转成NSData

//把UIView 转成Data    NSData *viewData = [NSKeyedArchiver archivedDataWithRootObject:self.myView];    [viewData writeToFile:@"/Users/shuan/Desktop/view.arch" atomically:YES];
    NSData *data = [NSData dataWithContentsOfFile:@"/Users/shuan/Desktop/view.arch"];    //通过反归档把 nsdata 转回对象    UIView *view = [NSKeyedUnarchiver unarchiveObjectWithData:data];

自定义对象归档:

//自定义对象要采纳NSCoding协议@interface Student : NSObject<NSCoding>@property (nonatomic, copy)NSString *name;@property (nonatomic)NSInteger age;@end
//实现NSCoding协议中的方法#import "Student.h"@implementation Student//实现编码方法 在方法中对每一个属性进行编码- (void)encodeWithCoder:(NSCoder *)aCoder{    [aCoder encodeObject:self.name forKey:@"name"];    [aCoder encodeInteger:self.age forKey:@"age"];}- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder{    self = [super init];    if (self) {        self.name = [aDecoder decodeObjectForKey:@"name"];        self.age = [aDecoder decodeIntegerForKey:@"age"];    }    return self;}@end
//    Student *s = [Student new];//    s.name = @"刘德华";//    s.age = 28;//    //    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:s];//    //    [data writeToFile:@"/Users/tarena/Desktop/student.arch" atomically:YES];//    反归档************    NSData *data = [NSData dataWithContentsOfFile:@"/Users/tarena/Desktop/student.arch"];    Student *s = [NSKeyedUnarchiver unarchiveObjectWithData:data];
0 0