2013-08-18 69 views
2

我無法跟蹤將NSDictionary對象數組寫入文件的問題。NSArray writeFileToPath失敗

NSDictionary對象中的每個鍵都是NSString s,值也是如此。所以數組應該可寫入plist,因爲文檔狀態是必需的。總之,這裏是我的代碼:

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

文件路徑的方法是這樣的:

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

和cacheID是字符串 「對象」。在運行時,filePathForCacheWithCacheID:方法返回像繩子:

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

可能是錯誤怎麼回事?

+0

什麼是您要寫入的文件路徑?我的意思是,在運行時,你的'filePathForCacheWithCacheID:'方法返回什麼值? –

+0

對於sim:file:///Users/MyName/Library/Application%20Support/iPhone%20Simulator/7.0/Applications/3A57A7B3-A522-4DCC-819B-DC8DEEDCD041/Library/Caches/objects –

回答

4

代碼正試圖將文件寫入表示文件URL而不是文件系統路徑的字符串。如果你想使用該方法,其中路徑字符串預期的返回值,你應該path替代absoluteString電話:

+ (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];