Ios 无法写入应用程序支持目录中的文件

Ios 无法写入应用程序支持目录中的文件,ios,objective-c,cocoa-touch,plist,nsfilemanager,Ios,Objective C,Cocoa Touch,Plist,Nsfilemanager,我正在尝试将一些值存储在iOS应用程序的应用程序支持目录中的plist中。但是写总是失败的。我使用了iOS文档中的锅炉板代码 在下面的代码中,我总是在执行writeToURL:atomically时出错。也就是说,我总是在日志中得到一个“未能写入plist”,并且永远不会创建该文件 URL似乎已正确创建。这是我在下面的URL打印中看到的存储plist的URL为file:///var/mobile/Containers/Data/Application/9E26C447-7562-438E-A38

我正在尝试将一些值存储在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.smartiothome.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) ;
}

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

NSError *error;
[sharedFM createDirectoryAtURL:appDirectory withIntermediateDirectories:NO attributes:nil error:&error];
这将创建目录


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

您是在模拟器上还是在真实设备上执行此操作?