你的位置:首页 > 操作系统

[操作系统]关于沙盒的读写文件的几种方式


@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    //    h获取应用沙盒

    NSString *homaPath =  NSHomeDirectory();

    NSLog(@"%@",homaPath);

}

 

/**

 * 下面的是用  plist  方式 保存 数据

 */

-(void)savePlist{

    NSString *homePath =  NSHomeDirectory();

    NSString *filePath = [homePath stringByAppendingPathComponent:@"Docments"];

    

    //    指定文件格式

    NSString *format = [filePath stringByAppendingPathComponent:@"xx.plist"];

    NSArray *data = @[@"房兰峰1",@"房兰峰2"];

    

    [data writeToFile:format atomically:YES];

 

    //    下面的是第二种方式---》系统提供的

    NSString *dataPath =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];

    NSString *filePathNssear = [dataPath stringByAppendingPathComponent:@"xx.plist"];

}

 

/**

 * 下面的是  plist 读取 数据

 */

-(void)readPlist{

    //  指定是哪个文件

    NSString *homePath = NSHomeDirectory();

    NSString *filePath = [homePath stringByAppendingPathComponent:@"Documents"];

    //    获取数据

    NSArray *data =  [NSArray arrayWithContentsOfFile:filePath];

}

 

 

//preference 方式  --->  偏好设置

-(void)preferenceSave{

    

    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];

    

    [ud setObject:@"value11" forKey:@"key1"];

    [ud setObject:@"value2" forKey:@"key2"];

    

    //    同步,一定要写这一步

    [ud synchronize];

}

/**

 * 下面是  preference  的读取方式

 */

-(void)preferenceRead{

    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];

    NSLog(@"%@",[ud objectForKey:@"key1"]);

    

}

/**

 * 数据的存储与读取 ====   >>>>>>   归档与解档

 */

-(void)keyedArchiverWrite{

    

    NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];

    NSString *filePath = [docPath stringByAppendingPathComponent:@"xx.data"];

    Teacher *teacher = [[Teacher alloc] init];

    teacher.name = @"垃圾";

    teacher.age = 10;

    

    //    归档

    [NSKeyedArchiver archiveRootObject:teacher toFile:filePath];

    

}

 

 

-(void)keyedUnarchiverRead{

    

    NSString *filePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];

    NSString *documentType = [filePath stringByAppendingPathComponent:@"xx.data"];

    Teacher *taecher =  [NSKeyedUnarchiver unarchiveObjectWithFile:documentType];

    

}

 

 

@end