使用NSKeyedArchiver,ios进行读写

时间:2012-07-24 17:14:16

标签: iphone nskeyedarchiver

以下是使用nsarchive

读写数据的类

Data.m

-(id)init {
    self        =   [super init];
    if(self) {
        arr     =   [[NSMutableArray alloc] init];
    }
    return self;
}

-(NSString *)getPath {
    NSArray     *paths          =   NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString    *documentPath;

    if ([paths count] > 0)
        documentPath            =   [paths objectAtIndex:0];

    NSString *draftDataPath     =   [documentPath stringByAppendingPathComponent:@"draftData.dat"];
    return draftDataPath;
}

-(void)saveDataToDisk {
    NSString *path              =   [self getPath];
    [NSKeyedArchiver archiveRootObject:arr toFile:path];

}

-(void)loadDataFromDisk {
    NSString    *path           =   [self getPath];
    self.arr                    =   [NSKeyedUnarchiver unarchiveObjectWithFile:path];
}

稍后,我会通过这样做将一些对象添加到arr中 CustomerClass.m

- (void) viewDidLoad {

Data *data = [[Data alloc] init];
[data.arr addObject:myObject1]
[data.arr addObject:myObject2]
[data.arr addObject:myObject3]
[data saveDataToDisk];
}

在DisplayData.m,我想通过

检查data.arr
- (void) viewDidLoad {
   Data *data = [[Data alloc] init];
   [data loadDataFromDisk];

   NSLog(@"length of array is %d",[data.arr count]);

}

在控制台上,我正在

length of array is 1

我认为它毕竟应该是3。

如果你有任何关于它的线索,请指出我在工作中犯了什么错误。

2 个答案:

答案 0 :(得分:5)

所以,我怀疑你的“myObjects”不符合NSCoding。我刚刚这样做了:

NSMutableArray *arr = [NSMutableArray arrayWithCapacity:3];
[arr addObject:@"Hello"];
[arr addObject:@" "];
[arr addObject:@"World"];
BOOL ret = [NSKeyedArchiver archiveRootObject:arr toFile:[self getPath]];

NSArray *arr2 = [NSKeyedUnarchiver unarchiveObjectWithFile:[self getPath]];
NSLog(@"count = %d", [arr2 count]);

结果是“count = 3”

答案 1 :(得分:3)

我觉得这里有太多的代码来做你想要的东西。我想你所需要的只是:

[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:dataClass] forKey:NSUserDefaultString];
[[NSUserDefaults standardUserDefaults] synchronize];

保存它。

NSData *someData = [[NSUserDefaults standardUserDefaults] objectForKey:NSUserDefaultString];
if (settingsData != nil)
{
    dataClass = [NSKeyedUnarchiver unarchiveObjectWithData:settingsData];
}

检索它。