Objective--C之《文件操作》练习代码

 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 }

 /*
 如果把自己定义的类所创建的对象直接写入文件的步骤:
 1) 自定义类遵循NSCoding协议,实现NSCoding协议中的两个方法:
    encodeWithCoder:往文件中写入实例变量
    initWithCoder:从文件中读取实例变量为当前对象赋值
 2) 如果把对象写入文件:调用NSKeyedArchiver中的archiveRootObject:toFile:
 3) 如果把对象从文件中读取出来:调用NSKeyedUnarchiver中的 unarchiveObjectWithFile:
 */

 1 #import <Foundation/Foundation.h>
 2 
 3 @interface Person : NSObject <NSCoding>
 4 
 5 //声明实例变量
 6 @property (nonatomic, strong) NSString *name;
 7 @property (nonatomic, assign) int age;
 8 
 9 - (id)init;
10 
11 @end
12 
13 #import "Person.h"
14 
15 @implementation Person
16 
17 - (id)init
18 {
19     if (self = [super init])
20     {
21         self.name = @"songlei";
22         _age = 18;
23     }
24     return self;
25 }
26 //归档(将数据存入文件)
27 - (void)encodeWithCoder:(NSCoder *)aCoder//往文件中写入实例变量
28 {
29     [aCoder encodeObject:_name forKey:@"0"];
30     [aCoder encodeObject:[NSNumber numberWithInt:_age] forKey:@"1"];
31 }
32 //解档并初始化(读取文件中的数据)
33 - (id)initWithCoder:(NSCoder *)aDecoder//从文件中读取实例变量为当前对象赋值
34 {
35     if (self = [super init])
36     {
37         self.name = [aDecoder decodeObjectForKey:@"0"];
38         _age = [[aDecoder decodeObjectForKey:@"1"] intValue];
39     }
40     return self;
41 }
42 
43 @end
44 
45 #import <Foundation/Foundation.h>
46 #import "Person.h"
47 
48 int main(int argc, const char * argv[])
49 {
50     @autoreleasepool
51     {
52 //        //创建一个NSFileManager对象
53 //        NSString *pathStr = [[NSFileManager defaultManager] currentDirectoryPath];//当前目录路径(也叫相对路径名)
54 //        NSString *realFile = [pathStr stringByAppendingString:@"/huashan.txt"];
55 //        [[NSFileManager defaultManager] createFileAtPath:realFile contents:nil attributes:nil];
56 //        NSLog(@"%@", pathStr);
57         NSString *str2 = @"/Users/hskj/Documents/mazi.txt";
58         [[NSFileManager defaultManager] createFileAtPath:str2 contents:nil attributes:nil];
59 //        NSString *str2 = [NSString stringWithFormat:@"%@/Documents/xiaoming.txt", NSHomeDirectory()];
60 //        [[NSFileManager defaultManager] createFileAtPath:str2 contents:nil attributes:nil];
61         
62         Person *p = [[Person alloc] init];
63         NSString *str1 = [NSString stringWithFormat:@"%@/Documents/xiaoming.txt", NSHomeDirectory()];
64         
65         [NSKeyedArchiver archiveRootObject:p toFile:str1];
66         
67         Person *p1 = [NSKeyedUnarchiver unarchiveObjectWithFile:str1];
68         NSLog(@"name: %@, age = %d", p1.name, p1.age);
69         NSData *data = [NSData dataWithContentsOfFile:str1];
70         NSLog(@"%@", data);
71         Person *p3 = [NSKeyedUnarchiver unarchiveObjectWithData:data];
72         NSLog(@"%@", p3.name);
73         
74         NSError *err = nil;
75         NSDictionary *attr = [[NSFileManager defaultManager] attributesOfItemAtPath:str1 error:&err];
76         NSLog(@"%@", attr);
77         
78         [[NSFileManager defaultManager] removeItemAtPath:str1 error:nil];
79         [[NSFileManager defaultManager] removeItemAtPath:str2 error:nil];
80         
81 
82     }
83     
84     return 0;
85 }
原文地址:https://www.cnblogs.com/songlei0601/p/5750789.html