标签:oc 归纳 让对象遵守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;
}
oc - NSFileHandle归纳,让对象遵守NSCoding协议,将对象存入数组,再通过解码输出
标签:oc 归纳 让对象遵守nscoding协议 将对象存入数组 再通过解码输出
原文地址:http://blog.csdn.net/zx6268476/article/details/45026235