oc NSFileHandle,文件读写管理类对对象数组的读写需信守协议
Person.m
#import "Person.h"
oc - NSFileHandle归纳,让对象遵守NSCoding协议,将对象存入数组,再通过解码输出
@implementation Person
// 编码
- (id)initWithCoder:(NSCoder *)aDecoder{
self = [superinit];
if (self) {
self.name = [[aDecoder decodeObjectForKey:@"name"]copy];// copy不变
self.age = [aDecoder decodeIntForKey:@"age"];
}
returnself;
}oc - NSFileHandle,文件读写管理类对对象数组的读写需遵守<NSCoding>协议
// 解码
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:self.nameforKey:@"name"];
[aCoder encodeInt:self.ageforKey:@"age"];
}
oc - NSFileHandle,文件读写管理类对对象数组的读写需遵守<NSCoding>协议
@end
oc - NSFileHandle归纳,让对象遵守NSCoding协议,将对象存入数组,再通过解码输出
main.m
#import <Foundation/Foundation.h>
int main(int argc,constchar * argv[]) {
@autoreleasepool {
NSString * path = [NSHomeDirectory() stringByAppendingPathComponent:@"desktop/jereh.txt"];
NSFileManager * manager = [NSFileManagerdefaultManager];
if (![managerfileExistsAtPath:path]) {
[manager createFileAtPath:path contents:nilattributes:nil];
NSFileHandle * fileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
// NSString * str = @"dsafas";
// NSData * data = [str dataUsingEncoding:NSUTF8StringEncoding];
[fileHandleseekToEndOfFile];
// [fileHandle writeData:data];
// 1.将数组写入文件
NSArray * array =@[@"jack",@"jim"];
// [array componentsJoinedByString:@"-"];
//自定义归纳
NSData * data2 = [NSKeyedArchiver archivedDataWithRootObject:array];
[fileHandle writeData:data2];
oc - NSFileHandle归纳,让对象遵守NSCoding协议,将对象存入数组,再通过解码输出
[fileHandle closeFile];
oc - NSFileHandle,文件读写管理类对对象数组的读写需遵守<NSCoding>协议
}else{
// 2.从数组中读出来
NSFileHandle * readHandle = [NSFileHandle fileHandleForReadingAtPath:path];
NSData * data = [readHandleavailableData];
NSArray * array = [NSKeyedUnarchiver unarchiveObjectWithData:data];
for (NSString * tepin array) {
NSLog(@"%@",tep);
}
oc - NSFileHandle,文件读写管理类对对象数组的读写需遵守<NSCoding>协议 oc - NSFileHandle归纳,让对象遵守NSCoding协议,将对象存入数组,再通过解码输出
[readHandle closeFile];
}
// 归纳
}
return0;
}