2

我无法追踪将NSDictionary对象数组写入文件的问题。

NSDictionary对象中的每个键都是NSStrings,值也是。因此,该数组应该可写入 plist,因为文档状态是必要的。无论如何,这是我的代码:

BOOL success = [representations writeToFile:[self filePathForCacheWithCacheID:cacheID] atomically:YES];
//success is NO

filePath 方法如下所示:

+ (NSString *)filePathForCacheWithCacheID:(NSString *)cacheID
{
    NSURL *cachesDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask] lastObject];
    return [[cachesDirectory URLByAppendingPathComponent:cacheID] absoluteString];
}

cacheID 是字符串“objects”。在运行时,该filePathForCacheWithCacheID:方法返回一个字符串,如:

file:///Users/MyName/Library/Application%20Support/iPhone%20Simulator/7.0/Applic‌​ations/3A57A7B3-A522-4DCC-819B-DC8DEEDCD041/Library/Caches/objects

这里可能出了什么问题?

4

1 回答 1

4

该代码试图将文件写入表示文件 URL 而不是文件系统路径的字符串。如果您希望在需要路径字符串的地方使用该方法的返回值,则应将absoluteString调用替换为path

+ (NSString *)filePathForCacheWithCacheID:(NSString *)cacheID
{
    NSURL *cachesDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask] lastObject];
    return [[cachesDirectory URLByAppendingPathComponent:cacheID] path];
}

或者,让filePathForCacheWithCacheID:方法返回一个NSURL然后使用该writeToURL:atomically:方法。

+ (NSURL *)fileURLForCacheWithCacheID:(NSString *)cacheID
{
    NSURL *cachesDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask] lastObject];
    return [cachesDirectory URLByAppendingPathComponent:cacheID];
}
...
BOOL success = [representations writeToURL:[self fileURLForCacheWithCacheID:cacheID] atomically:YES];
于 2013-08-18T04:31:08.130 回答