本文共 3362 字,大约阅读时间需要 11 分钟。
沙盒机制(SandBox)是iOS系统中的一个关键安全机制。它规定每个应用程序只能在自己专用的沙盒内存储和访问文件,无法跨越沙盒访问其他应用程序的内容。这种机制确保了应用程序的安全性和数据的孤立性。
在沙盒中,主要包括以下几个目录:
获取主目录:
NSString *path = NSHomeDirectory();
获取应用程序的路径:
NSString *bundlePath = [NSBundle mainBundle].bundlePath;
获取Document目录:
NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, NO) lastObject];
改动后面的NO
与YES
可以看到不同的路径表现
获取Caches目录:
NSString *cache = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, NO) lastObject];
获取Temporary目录:
NSString *tem = NSTemporaryDirectory();
Plist文件是iOS中常用的数据存储格式,起到类似数据库的作用,但不支持对象存储。主要用途包括保存用户设置和必要的应用数据。
NSString *savePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"data.plist"];NSArray *arr = [NSArray arrayWithObjects:@"hensen",@"java", nil];[arr writeToFile:savePath atomically:YES];
NSString *savePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"data.plist";NSArray *getArr = [NSArray arrayWithContentsOfFile:savePath];NSString *myName = getArr[0];NSString *myLaugage = getArr[1];
Perference(偏好设置)用于存储应用的用户偏好配置,通常使用NSUserDefaults进行管理。该目录由系统管理,类似Keychain,需谨慎对待。
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];[defaults setInteger:18 forKey:@"age"];[defaults setObject:@"hensen" forKey:@"name"];[defaults synchronize];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];NSInteger *age = [defaults integerForKey:@"age"];NSString *name = [defaults objectForKey:@"name"];
归档和反归档通过NSCoding协议实现对象的序列化和反序列化,弥补了Plist和Perference存储对象的短板。
@interface PersonModel : NSObject@property (strong,nonatomic) NSString *name;@property (assign,nonatomic) NSInteger age;@end
@interface PersonModel@end
-(nullable instancetype)initWithCoder:(NSCoder *)aDecoder{ if(self = [super init]){ self.name = [aDecoder decodeObjectForKey:@"name"]; self.age = [aDecoder decodeIntegerForKey:@"age"]; } return self;}
NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];NSString *fileName = [filePath stringByAppendingPathComponent:@"con.plist"];PersonModel *model = [[PersonModel alloc] init];model.name = @"hensen";model.age = 18;[NSKeyedArchiver archiveRootObject:model toFile:fileName];
##Five 反归档反归档即解包操作,核心是使用NSCoding协议恢复模型对象。
-(void)encodeWithCoder:(NSCoder *)aCoder{ [aCoder encodeObject:self.name forKey:@"name"]; [aCoder encodeInteger:self.age forKey:@"age"];}
NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];NSString *fileName = [filePath stringByAppendingPathComponent:@"con.plist"]; PersonModel *person = [NSKeyedUnarchiver unarchiveObjectWithFile:fileName]; NSLog(@"name:%@,age:%ld", person.name, (long)person.age);
通过合理运用沙盒机制、Plist、Perference、归档和反归档,可以有效管理iOS应用中的数据存储需求。尽管理论知识无误,但实际开发中建议根据具体项目需求灵活调整。
转载地址:http://oevrz.baihongyu.com/