NSApplicationSupportDirectory无效的CFStringRef

时间:2012-04-27 16:17:11

标签: objective-c ios xcode file nsapplication

我正在尝试将文件存储在NSApplicationSupportDirectory中,因为我的应用程序中有一个预加载的文件夹,我想在应用程序初始化后添加文件。我正在尝试NSLog文件的内容,所以我可以看看它是否真的有效。从调试器,我可以看到内容是,我不是什么意思。任何人

NSString *document = [NSString stringWithFormat:@"%@ %@ %@ %@ %@", description, focus, level, equipment, waterDepth];

//NSLog(@"%@", document);

//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *supportDirectory = [paths objectAtIndex:0];

//filename
NSString *filename = [NSString stringWithFormat:@"%@/%@", supportDirectory,[_nameTextField.text stringByAppendingString:@".txt"]];
NSLog(@"%@", supportDirectory);
NSLog(@"%@", filename);

[document writeToFile:filename atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil];

NSString *content = [[NSString alloc]initWithContentsOfFile:filename usedEncoding:nil error:nil];
NSLog(@"%@", content);

2 个答案:

答案 0 :(得分:9)

您没有传递字符串编码,而是传递NSStringEncodingConversionAllowLossy,这可能会影响某些方法(不是您正在使用的方法)的编码转换方式。您需要传递NSUTF8StringEncoding

之类的内容

答案 1 :(得分:1)

当您编写或读取文件时,强烈建议您使用error参数并处理出现错误的情况。此外,这对于帮助您调试代码非常有用。

例如,在您的情况下,您可以这样做:

NSError *error = nil;
BOOL success = [document writeToFile:filename atomically:NO encoding:NSStringEncodingConversionAllowLossy error:&error];

if (!success) {
    NSLog(@"Could not write file: %@", error);
} else {
    NSString *content = [[NSString alloc]initWithContentsOfFile:filename usedEncoding:nil error:&error];
    if (!content) {
        NSLog(@"Could not read file: %@", error);
    }
}

如果您收到错误消息The operation couldn’t be completed. No such file or directory,则表示您之前未创建该文件夹。因此,在尝试向其添加内容之前创建它:

NSString *supportDirectory = [paths objectAtIndex:0];
NSError *error = nil;
BOOL success;
if (![[NSFileManager defaultManager] fileExistsAtPath: supportDirectory]) {
    success = [[NSFileManager defaultManager] createDirectoryAtPath:supportDirectory withIntermediateDirectories:YES attributes:nil error:&error];
    if (!success) {
        NSLog(@"Could not create directory: %@", error);
    }
}