0

因此,我的应用程序查询了一个 Amazon Dynamo DB 数据库并检索了几千字节的数据。我希望应用程序做的是第一次下载所有内容,然后每次下载一个时间戳,看看它是否有最新版本的数据。所以我只需要每隔一段时间下载一次数据,我正在尝试使用 NSKeyedArchiver 来存档我正在下载的数组。我已经尝试了这三种不同的方法,但它们都不能在 iPhone 上运行,尽管其中两种可以在模拟器上运行。

[NSKeyedArchiver archiveRootObject:self.dataArray toFile:@"dataArray.archive"];

这不适用于模拟器或实际的 iphone。这种方法的结果是否定的。

我使用的下一件事是完整路径:

[NSKeyedArchiver archiveRootObject:self.dataArray toFile:@"Users/Corey/Desktop/.../dataArray.archive"];

这适用于模拟器,但不适用于 iPhone。我的猜测是,编译时,文件系统看起来不同(并且显然没有相同的路径)。所以接下来我尝试了:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"dataArray" ofType:@".archive"];

[NSKeyedArchiver archiveRootObject:self.dataArray toFile:filePath];

再一次,这在模拟器上有效,但在 iphone 上失败。在写入存档之前,我已经确认所有数据都在 self.dataArray 中,并在写回存档后确认数组为零(在 iphone 版本中)。有什么想法吗?有没有更好的方法来做文件路径?

4

2 回答 2

1

这是我追查到的:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent: @"dataArray.archive"];
[NSKeyedArchiver archiveRootObject:your_object toFile:filePath];

它在模拟器和 iPhone 上都能完美运行!

于 2014-08-15T21:13:18.763 回答
0
[NSKeyedArchiver archiveRootObject:self.dataArray toFile:@"dataArray.archive"];

您必须提供完整路径。

[NSKeyedArchiver archiveRootObject:self.dataArray toFile:@"Users/Corey/Desktop/.../dataArray.archive"];

这不是一条完整的路径。一条完整的路径始于/并且没有/../任何地方。

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"dataArray" ofType:@".archive"];

您没有权限在 mainBundle 中写入,它是只读的。

此外,通常您不应该使用文件路径,而应该使用 URL。一些 API(包括这个 API)需要路径,但现在推荐使用 URL。

以下是将文件写入磁盘的正确方法:

NSURL *applicationSupportUrl = [[NSFileManager defaultManager] URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask][0];

applicationSupportUrl = [applicationSupportUrl URLByAppendingPathComponent:@"My App"]; // replace with your app name

if (![applicationSupportUrl checkResourceIsReachableAndReturnError:NULL]) {
  [[NSFileManager defaultManager] createDirectoryAtURL:applicationSupportUrl withIntermediateDirectories:YES attributes:@{} error:NULL];
}

NSURL *archiveUrl = [applicationSupportUrl URLByAppendingPathComponent:@"foo.archive"];
[NSKeyedArchiver archiveRootObject:self.dataArray toFile:archiveUrl.path];
于 2014-08-12T23:45:44.480 回答