Objc文件读写

Objc文件读写

在ios开发中处理文件的时候也很多,其作为一种数据持久化方式起到了至关重要的作用,各个 语言的文件处理都大同小异,但是IOS处理文件的方式却很特别,下面就来详细总结一下objc 处理文件的一般用法。

文件目录

IOS程序是运行在应用沙盒之中,每个APP均会有一个专属沙盒,这样各个APP就不会互相干扰, APP也不能访问沙盒之外的文件,一定程度上保证了APP运行的安全。那么,我们如何获得沙盒 中的文件目录?

//获取App主路径~
NSString *homePath =NSHomeDirectory();

//获取~/Documents
NSArray *documentArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, NO);
NSString *documentPath = [documentArray firstObject];

//获取~/Library
NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];

//获取~/Library/Caches
NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)firstObject];

//获取~/Library/Preferences
NSString *preferencePath =[libraryPath stringByAppendingString:@"/Preferences"];

//获取~/tmp
NSString *tmpPath = NSTemporaryDirectory();

上面是我们在编码过程中使用的常用路径,还有一点对于初学者来说容易混淆,就是我们在 代码中使用的一些资源文件,即静态文件,处于Bundle管理下,IOS8之后,Bundle不再处于 home目录之下。

//获得Bundle主目录
NSString *path = [NSBundle mainBundle].resourcePath;
NSString *path = [NSBundle mainBundle].bundlePath;

在App启动时,会将资源文件拷贝到Bundle主目录下,所以在使用过程中我们只需要关心文件 名即可。

简单对象写入

IOS开发者一定很熟悉NSUserDefaults,它可以让我们方便地对简单数据进行存储,其是一个 单例对象,文件实际存储的位置在于~/Library/Preferences目录下,适合于存储轻量级的本地 数据,比如用户名、密码之类的,支持的数据类型如下:

NSNumber ( Integer、Float、Double )
NSString
NSArray
NSDictionary
BOOL类型
NSDate

使用NSUserDefaults的本质还是写入文件,对于NSString、NSArray、NSDictionary和NSData 这四种对象的数据可以直接写入文件中:

[string writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
[array writeToFile:docuPath atomically:YES];
[dict writeToFile:prefePath atomically:YES];
[data writeToFile:homePath atomically:YES];

对于上述简单对象,其嵌套的类型也必须是简单类型。再者,Objc是c语言的超集,c语言中 一些处理文件的API在这里同样适用,

NSString *path = NSTemporaryDirectory();
FILE *file = fopen([path cStringUsingEncoding:NSASCIIStringEncoding], "rb");
UInt64 temp64;
fread(&temp64, sizeof(UInt64), 1, file);

UInt64 temp64 = [key longLongValue];
fwrite(&temp64, sizeof(UInt64), 1, file);

不要以为C中的繁琐,当我们需要向文件中追加数据或者定位数据的文件位置时,推荐使用c 的API,这样既简单又高效。

复杂对象归档

复杂对象并不是Foundation框架内的对象,自然也就无法使用writeFile对象来写入文件中, 但是我们可以将复杂对象转化为NSData,然后写入文件,读取的时候也是读取的NSData,然后 再转化为一般的对象,这种转化的过程即为归档。

使用归档的一般步骤为,遵守NSCoding协议,实现其中的两个方法。如下:

@interface Person:NSObject<NSCoding> 
     @property(nonatomic,copy) NSString *name 
     @property(nonatomic,assign) integer age; 
@end

// 对person对象进行归档时,此方法执行。
// 对person中想要进行归档的所有属性,进行序列化操作
-(void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeInteger:self.age forKey:@"age"];
}
// 对person对象进行反归档时,该方法执行。
// 创建一个新的person对象,所有属性都是通过反序列化得到的。
-(id)initWithCoder:(NSCoder *)aDecoder 
{
    self = [super init];
    if (self) {
        self.name = [aDecoder decodeObjectForKey:@"name"];
        self.age = [aDecoder decodeIntegerForKey:@"age"];
    }
return self;
}

然后使用NSKeyedArchiver类来进行归档,常用的API如下:

1. 方法一:
// 准备一个NSMutableData, 用于保存归档后的对象
NSMutableData *data = [NSMutableData data];
// 创建归档工具
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingMutableData:data];
// 归档
[archiver encodeObject:p] forKey:@"p1"];
// 结束
[archiver finishEncoding];
// 写入沙盒
[data writeToFile:filePath atomically:YES];

2.方法二:
BOOL archiveSuccess = [NSKeyedArchiver archiveRootObject:person toFile:path];

3. 方法三:
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:person];
[data writeToFile:filePath atomically:YES];

上述API中显然方法二最简单,所以一般使用方法二。反归档一般如下使用:

Person* person = [NSKeyedUnarchiver unarchiveObjectWithFile:path];

NSFileManager

苹果将文件操作封装成了一个单例类,其API如下:

//判断一个文件是否存在
BOOL fileExists = [fileManager fileExistsAtPath:filePath];

//创建一个目录
if (![fileManager fileExistsAtPath:imagesPath]) {
    [fileManager createDirectoryAtPath:imagesPath withIntermediateDirectories:NO attributes:nil error:nil];
}

//删除一个目录
if (![fileManager removeItemAtPath:filePath error:&error]) {
    NSLog(@"[Error] %@ (%@)", error, filePath);
}

当然文件操作API还有很多,比如遍历一个目录等等,请参考:http://nshipster.cn/nsfilemanager/

总结

文件操作是写代码必须掌握的部分,重要性无需累述。



Previous     Next
zhing /
Published under (CC) BY-NC-SA in categories ios  tagged with ios