1

下面是一个使用nsarchive读写数据的类

数据.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毕竟。

如果您有任何线索,请指出我在工作中犯的错误。

4

2 回答 2

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”

于 2012-07-24T17:56:28.197 回答
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];
}

检索它。

于 2012-07-24T17:31:01.510 回答