OGeek|极客世界-中国程序员成长平台

标题: ios - NSArray writeFileToPath 失败 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 03:38
标题: ios - NSArray writeFileToPath 失败

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

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

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

filePath 方法如下所示:

+ (NSString *)filePathForCacheWithCacheIDNSString *)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

这里可能出了什么问题?



Best Answer-推荐答案


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

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

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

+ (NSURL *)fileURLForCacheWithCacheIDNSString *)cacheID
{
    NSURL *cachesDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask] lastObject];
    return [cachesDirectory URLByAppendingPathComponent:cacheID];
}
...
BOOL success = [representations writeToURL:[self fileURLForCacheWithCacheID:cacheID] atomically:YES];

关于ios - NSArray writeFileToPath 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18295305/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4