Foundation对象 <-> 文件
NSArray *array = @[@1,@2,@3];
[array writeToFile:kFileAddress
atomically:YES];
NSDictionary *dictionary = @{@"1" : @1 , @"2" : @2 , @"3" : @3};
[dictionary writeToFile:kFileAddress
atomically:YES];
NSString *string = @"hello world";
[string writeToFile:kFileAddress
atomically:YES // 是否先将内容写入临时文件,成功后再将临时文件目标文件交换
encoding:NSUTF8StringEncoding
error:&writeToFileError];
if (writeToFileError) {
NSLog(@"%@",[writeToFileError localizedDescription]);
writeToFileError = nil;
}
NSData *data = [[NSData alloc] init];
[data writeToFile:kFileAddress
options:NSDataWritingAtomic // 先将内容写入临时文件,成功后再把临时文件和目标文件交换
error:&writeToFileError];
if (writeToFileError) {
NSLog(@"%@",[writeToFileError localizedDescription]);
writeToFileError = nil;
}
自定义对象 <-> NSData <->文件
- 自定义类遵循 NSCoding 协议,实现 encodeWithCoder:和 initWithCoder:方法
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:self.name forKey:kKeyForName];
[aCoder encodeObject:self.phoneNumber forKey:kKeyForPhoneNumber];
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
self = [super init];
if (self) {
self.name = [aDecoder decodeObjectForKey:kKeyForName];
self.phoneNumber = [aDecoder decodeObjectForKey:kKeyForPhoneNumber];
}
return self;
}
- 用 NSCoder 子类 NSKeyedArchiver 和 NSKeyedUnarchiver
// 将 ZWQPerson 对象写入文件
ZWQPerson *personA = [[ZWQPerson alloc] initWithName:@"David" phoneNumber:@12345678912];
NSError *writeToFileError = nil;
NSData *dataOfZWQPersonA = [NSKeyedArchiver archivedDataWithRootObject:personA];
[dataOfZWQPersonA writeToFile:kFileAddress
options:NSDataWritingAtomic
error:&writeToFileError];
if (writeToFileError) {
NSLog(@"%@",[writeToFileError localizedDescription]);
}
// 从文件中读取 ZWQPerson
NSData *dataOfZWQPersonB = [NSData dataWithContentsOfFile:kFileAddress];
ZWQPerson *personB = [NSKeyedUnarchiver unarchiveObjectWithData:dataOfZWQPersonB];
NSLog(@"If personA is equal to personB? %@", [personA isEqualToPerson:personB] ? @"YES" : @"NO" ); // 应该返回 YES