【问题标题】:unable to write to a file in AplicationSupport directory无法写入 AplicationSupport 目录中的文件
【发布时间】:2016-02-17 07:27:33
【问题描述】:

我正在尝试将一些值存储在我的 iOS 应用程序的应用程序支持目录中的 plist 中。但是写入总是失败。我使用了 iOS 文档中的样板代码。

在下面的代码中,我在执行 writeToURL:atomically 时总是遇到错误。即,我总是在日志中收到“无法写入 plist”,并且永远不会创建文件。

该 URL 似乎已正确创建。这是我在下面的 URL 打印中看到的。 存储 plist 的 URL 是 file:///var/mobile/Containers/Data/Application/9E26C447-7562-438E-A38A-E8F04C6DAFFE/Library/Application%20Support/com.apm.smartiohome.chatime/ bcastSeqNum.plist

如果我做错了什么,我将不胜感激。

 NSFileManager* sharedFM = [NSFileManager defaultManager];
NSArray* possibleURLs = [sharedFM URLsForDirectory:NSApplicationSupportDirectory
                                         inDomains:NSUserDomainMask];
NSURL* appSupportDir = nil;
NSURL* appDirectory = nil;

if ([possibleURLs count] >= 1) {
    // Use the first directory (if multiple are returned)
    appSupportDir = [possibleURLs objectAtIndex:0];
}

// If a valid app support directory exists, add the
// app's bundle ID to it to specify the final directory.
if (appSupportDir)
{
    NSString* appBundleID = [[NSBundle mainBundle] bundleIdentifier];
    appDirectory = [appSupportDir URLByAppendingPathComponent:appBundleID];
}
else
{
    DDLogError(@"Could not get pointer to app support directory") ;
}

self.bcastSeqNumFilePtr = [appSupportRootPtr URLByAppendingPathComponent:@"bcastSeqNum.plist" isDirectory:NO];

NSMutableArray *arrToReturn ;

arrToReturn = [NSMutableArray arrayWithContentsOfURL:self.bcastSeqNumFilePtr] ;

if(!arrToReturn)
{
    /*File does not exist...create one*/
    DDLogVerbose(@"Bcast seq num file does not exist.  Creating bcast plist file") ;
    NSMutableDictionary *dictToStore = [[NSMutableDictionary alloc] init] ;
    NSMutableArray *arrToReturn = [[NSMutableArray alloc] init] ;
    [arrToReturn addObject:[NSNumber numberWithInt:-1]] ;
    [dictToStore setObject:arrToReturn forKey:@"Bcast Seq Numbers"] ;
    if(![dictToStore writeToURL:self.bcastSeqNumFilePtr atomically:YES])
    {
        DDLogError(@"Failed to write to plist.") ;
    }
}
else
{
    DDLogVerbose(@"Bcase seq num file exists. returning seq number list from it %@",arrToReturn) ;
}

【问题讨论】:

  • 你是在模拟器上还是在真机上执行这个?

标签: ios objective-c cocoa-touch plist nsfilemanager


【解决方案1】:

问题在于 writeToURL 不会在路径中为您创建任何缺失的目录。如果你打电话:

NSError *error;
[sharedFM createDirectoryAtURL:appDirectory withIntermediateDirectories:NO attributes:nil error:&error];

这将创建目录。

一个问题,为什么要将 bundleIdentifier 添加到路径中?您获得的应用程序支持目录已经是您应用程序沙箱的私有目录。如果不添加,则不需要创建目录。

【讨论】:

    猜你喜欢
    • 2018-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    • 2011-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-30
    相关资源
    最近更新 更多