1 #import <Foundation/Foundation.h> 2 3 @interface Baby : NSObject <NSCoding> 4 //声明实例变量 5 @property (nonatomic, assign) int age; 6 @property (nonatomic, retain) NSString *name; 7 @property (nonatomic, assign) double score; 8 9 - (id)initWithAge:(int)a andName:(NSString *)n andScore:(double)s; 10 11 - (void)print; 12 13 @end 14 15 #import "Baby.h" 16 17 @implementation Baby 18 19 - (id)initWithAge:(int)a andName:(NSString *)n andScore:(double)s 20 { 21 if (self = [super init]) 22 { 23 _age = a; 24 self.name = n; 25 _score = s; 26 } 27 return self; 28 } 29 //归档(将数据存入文件) 30 - (void)encodeWithCoder:(NSCoder *)aCoder//往文件中写入实例变量 31 { 32 [aCoder encodeObject:[NSNumber numberWithInt:_age] forKey:@"1"]; 33 [aCoder encodeObject:_name forKey:@"2"]; 34 [aCoder encodeObject:[NSNumber numberWithDouble:_score] forKey:@"3"]; 35 } 36 //解档并初始化(读取文件中的数据) 37 - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder//从文件中读取实例变量为当前对象赋值 38 { 39 if (self = [super init]) 40 { 41 _age = [[aDecoder decodeObjectForKey:@"1"] intValue]; 42 self.name = [aDecoder decodeObjectForKey:@"2"]; 43 _score = [[aDecoder decodeObjectForKey:@"3"] doubleValue]; 44 } 45 return self; 46 } 47 48 49 - (void)print 50 { 51 NSLog(@"Age = %d, Name = %@, Score = %.2lf", _age, self.name, _score); 52 } 53 54 - (void)dealloc 55 { 56 [_name release]; 57 [super dealloc]; 58 } 59 60 @end 61 62 #import <Foundation/Foundation.h> 63 #import "Baby.h" 64 int main(int argc, const char * argv[]) { 65 @autoreleasepool 66 { 67 #pragma mark - 管理文件和目录 68 //创建一个NSFileManager对象 69 NSFileManager *fm = [NSFileManager defaultManager]; 70 NSError *err = nil; 71 NSDictionary *attr = [fm attributesOfItemAtPath:@"filePath" error:&err]; 72 //从属性字典里取出一个特定的属性:文件大小 73 int filesize = [[attr objectForKey:NSFileSize] intValue]; 74 NSData *data = [fm contentsAtPath:@"/Users/hskj/AddressCard.txt"]; 75 // AddressCard *card1 = [NSKeyedUnarchiver unarchiveObjectWithData:data]; 76 // NSLog(@"card1 %@", card1); 77 [fm createFileAtPath:@"/Users/hskj/AddressCard.txt" contents:data attributes:nil]; 78 //removeItemAtPath:error:删除指定的文件, 如: 79 [fm removeItemAtPath:@"/Users/hskj/AddressCard.txt" error:&err]; 80 //fileExistsAtPath:判断指定文件是否存在,如 81 [fm fileExistsAtPath:@"/Users/hskj/AddressCard.txt"]; 82 //copyItemAtPath:toPath:error: 把第一个参数中指定的文件内容拷贝到toPath指定的文件中,如: 83 [fm copyItemAtPath:@"/Users/hskj/AddressCard1.txt" toPath:@"/Users/hskj/AddressCard2.txt" error:&err]; 84 85 #pragma mark - NSCoding协议例题 86 Baby *b = [[Baby alloc] initWithAge:23 andName:@"songlei" andScore:99 ]; 87 [b print]; 88 89 NSString *pathDirectory = [NSString stringWithFormat:@"%@/Users/hskj/songlei.txt", NSHomeDirectory()]; 90 //归档类:把对象b归档到此文件中去(此时系统会自动调用协议中的归档方法) 91 [NSKeyedArchiver archiveRootObject:b toFile:pathDirectory]; 92 //解档类:把对象b1从此文件中去取出(此时系统会自动调用协议中的接档方法) 93 Baby *b1 = [NSKeyedUnarchiver unarchiveObjectWithFile:pathDirectory]; 94 [b1 print]; 95 } 96 return 0; 97 }
时间: 2024-10-26 08:34:19