oc - NSFileHandle归纳,让对象遵守NSCoding协议,将对象存入数组,再通过解码输出
Person.m
#import "Person.h"
@implementation Person
// 编码
- (id)initWithCoder:(NSCoder *)aDecoder{
self = [super init];
if (self) {
self.name = [[aDecoder decodeObjectForKey:@"name"]copy];// copy不变
self.age = [aDecoder decodeIntForKey:@"age"];
}
return self;
}
// 解码
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeInt:self.age forKey:@"age"];
}
@end
main.m
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSString * path = [NSHomeDirectory() stringByAppendingPathComponent:@"desktop/jereh.txt"];
NSFileManager * manager = [NSFileManager defaultManager];
if (![manager fileExistsAtPath:path]) {
[manager createFileAtPath:path contents:nil attributes:nil];
NSFileHandle * fileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
// NSString * str = @"dsafas";
// NSData * data = [str dataUsingEncoding:NSUTF8StringEncoding];
[fileHandle seekToEndOfFile];
// [fileHandle writeData:data];
// 1.将数组写入文件
NSArray * array = @[@"jack",@"jim"];
// [array componentsJoinedByString:@"-"];
// 自定义归纳
NSData * data2 = [NSKeyedArchiver archivedDataWithRootObject:array];
[fileHandle writeData:data2];
[fileHandle closeFile];
}else{
// 2.从数组中读出来
NSFileHandle * readHandle = [NSFileHandle fileHandleForReadingAtPath:path];
NSData * data = [readHandle availableData];
NSArray * array = [NSKeyedUnarchiver unarchiveObjectWithData:data];
for (NSString * tep in array) {
NSLog(@"%@",tep);
}
[readHandle closeFile];
}
// 归纳
}
return 0;
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。