2

NSDictionaryオブジェクトの配列をファイルに書き込む際の問題を突き止めるのに苦労しています。

NSDictionaryオブジェクトの各キーNSStringは、値と同様に です。したがって、ドキュメントに記載されているように、配列は 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 に答える