Fork me on GitHub

使用NSKeyedArchiver 及NSCoding保存数据

- (NSMutableArray *)loadMarkersFromFilePath:(NSString *)filePath {
    NSMutableArray *markers = nil;
    if (filePath == nil || [filePath length] == 0 || 
        [[NSFileManager defaultManager] fileExistsAtPath:filePath] == NO) {
        markers = [[[NSMutableArray alloc] init] autorelease];
    } else {
        NSData *data = [[NSData alloc] initWithContentsOfFile:filePath];
        NSKeyedUnarchiver *vdUnarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
        markers = [vdUnarchiver decodeObjectForKey:kSaveKeyMarkerLines];
        [vdUnarchiver finishDecoding];
        [vdUnarchiver release];
        [data release];
    }
    return markers;

}

 

 

 


- (void)saveMarkers:(NSMutableArray *)markers toFilePath:(NSString *)filePath {
    NSMutableData *data = [[NSMutableData alloc] init];
    NSKeyedArchiver *vdArchiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [vdArchiver encodeObject:markers forKey:kSaveKeyMarkerLines];
    [vdArchiver finishEncoding];
    [data writeToFile:filePath atomically:YES];
    [vdArchiver release];
    [data release];

}

 

 

==================================================================================

[NSString stringWithContentsOfFile:filepath encoding:NSUTF8StringEncoding error:nil];

 

 

-----------------------------------------------------------------------------------------------------------------------------------------------

 

 1 /*======================================================= 
2 NSKeyedArchiver
3 ========================================================*/
4 NSString *str = @"abc";
5 NSString *astr = @"efg";
6 NSArray *Array = [NSArray arrayWithObjects:str, astr, nil];
7
8 //Save
9 NSString *Path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *filename = [Path stringByAppendingPathComponent:@"test"];
10 [NSKeyedArchiver archiveRootObject:Array toFile:filename];
11//NSData *data =[NSKeyedArchiver archivedDataWithRootObject:Array];
12 str = @"a";  
13 astr = @"";
14
15 //load
16 NSArray *arr = [NSKeyedUnarchiver unarchiveObjectWithFile: filename];
17 str = [arr objectAtIndex:0];
18 astr = [arr objectAtIndex:1];
19
20 NSLog(@"str:%@",str);
21 NSLog(@"astr:%@",astr);
22
23 /*=======================================================
24 NSUserDefaults
25 ========================================================*/
26 NSString *str = @"abc";
27 NSString *astr = @"efg";
28 NSArray *Array = [NSArray arrayWithObjects:str, astr, nil];
29
30 //Save
31 NSUserDefaults *SaveDefaults = [NSUserDefaults standardUserDefaults];
32 [SaveDefaults setObject:Array forKey:@"SaveKey"];
33
34 str = @"a";
35 astr = @"";
36
37 //load
38 Array = [SaveDefaults objectForKey:@"SaveKey"];
39 str = [Array objectAtIndex:0];
40 astr = [Array objectAtIndex:1];
41 NSLog(@"str:%@",str);
42 NSLog(@"astr:%@",astr);
43
44 /*=======================================================
45 writeToFile:
46 ========================================================*/
47 NSString *str = @"abc";
48 NSString *astr = @"efg";
49 NSArray *Array = [NSArray arrayWithObjects:str, astr, nil];
50
51 //Save
52 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
53 NSString *documentsDirectory = [paths objectAtIndex:0];
54 if (!documentsDirectory) {
55 NSLog(@"Documents directory not found!");
56 }
57 NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"Savedatas.plist"];
58 [[NSArray arrayWithObjects:Array,nil] writeToFile:appFile atomically:NO];
59
60
61 //load
62 if([[NSFileManager defaultManager] fileExistsAtPath:appFile])
63 self.SaveDataArray = [NSMutableArray arrayWithContentsOfFile:appFile];
64 else
65 self.SaveDataArray = [NSMutableArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Savedatas" ofType:@"plist"]];
66 NSArray *strArray = [self.SaveDataArray objectAtIndex:0];
67
68 str = [strArray objectAtIndex:0];
69 astr = [strArray objectAtIndex:1];
75 //坛子里的,搬过来。。。。。  
76 -(BOOL) writeApplicationData:(NSDictionary *)data writeFileName:(NSString *)fileName
77 {
78 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
79 NSString *documentsDirectory = [paths objectAtIndex:0];
80 if (!documentsDirectory) {
81 NSLog(@"Documents directory not found!");
82 return NO;
83 }
84 NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
85 return ([data writeToFile:appFile atomically:YES]);
86 }
87
88 -(id) readApplicationData:(NSString *)fileName
89 {
90 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
91 NSString *documentsDirectory = [paths objectAtIndex:0];
92 NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
93 NSDictionary *myData = [[[NSDictionary alloc] initWithContentsOfFile:appFile] autorelease];
94 return myData;
95 }

 

NSCoding 保存数据

为了将应用数据存储到硬盘中,iOS提供基本的文件API、Property List序列化、SQLite、CoreData以及NSCoding。对于轻量级的数据要求,NSCoding因其简单而成为一种比较合适的方式。

     NSCoding是一个你需要在数据类上要实现的协议以支持数据类和数据流间的编码和解码。数据流可以持久化到硬盘。而实现NSCoding其实很简单,因此有时会很有用。相关代码如下:

 

 1 // 键值宏定义  
2 #define SAMPLEDATA_KEY_STARS (@"stars")
3 #define SAMPLEDATA_KEY_TITLE (@"title")
4 #define SAMPLEDATA_KEY_ITEMS (@"items")
5
6 @interface SampleData : NSObject <NSCoding>{
7 int starCount;
8 NSString *titleText;
9 NSMutableDictionary *items;
10 int tempNumber; //不保存的变量
11 }
12 @property(nonatomic,readwrite) int starCount;
13 @property (nonatomic, retain, readwrite) NSString *titleText;
14 @property (nonatomic, retain, readwrite) NSMutableDictionary *items;
15 @property(nonatomic,readwrite) int tempNumber;
16 @end
17
18 @implementation SampleData
19 @synthesize starCount, titleText, items, tempNumber;
20
21 - (void)encodeWithCoder:(NSCoder*)coder
22 {
23 [coder encodeObject:titleText forKey:SAMPLEDATA_KEY_TITLE];
24 [coder encodeObject:items forKey:SAMPLEDATA_KEY_ITEMS];
25 [coder encodeInt:starCount forKey:SAMPLEDATA_KEY_STARS];
26 }
27 - (id)initWithCoder:(NSCoder*)decoder
28 {
29 if ((self = [super init])){ //被init:调用时使用默认值
30 self.titleText = nil;
31 self.items = [[NSMutableDictionary alloc]init];
32 starCount = 0;
33 tempNumber = 0;
34 if (decoder==nil) {
35 return self;
36 }
37
38 // 取值前确认相应的键值是否存在。
39 if ([decoder containsValueForKey:SAMPLEDATA_KEY_TITLE]) {
40 self.titleText = [decoder decodeObjectForKey:SAMPLEDATA_KEY_TITLE];
41 }
42 if ([decoder containsValueForKey:SAMPLEDATA_KEY_ITEMS]) {
43 self.items = [decoder decodeObjectForKey:SAMPLEDATA_KEY_ITEMS];
44 }
45 if ([decoder containsValueForKey:SAMPLEDATA_KEY_STARS]) {
46 starCount = [decoder decodeIntForKey:SAMPLEDATA_KEY_STARS];
47 }
48 }
49 return self;
50 }
51 - (id)init {
52 if ((self = [super init])){
53 [self initWithCoder:nil];
54 }
55 return self;
56 }
57 @end

 

      就这些! 其中我们需要实现两个方法: encodeWithCoder和initWithEncoder。

encodeWithCoder就是编码,initWithCoder就是解码。

encodeWithCoder方法传入的是一个NSCoder对象,实现的时候我们就可以调用encodeObject、encodeFloat、encodeInt等各种方法并通过指定键值进行编码。

posted on 2012-02-12 11:07  pengyingh  阅读(8332)  评论(0编辑  收藏  举报

导航