在ios上写:文件没有出现

时间:2011-11-25 17:26:38

标签: ios

我想为外部文件写一些值,并为此目的使用NSDictionary:

NSString *s = @"123456";
NSString *key = @"key";
NSString *file = pathInAppDirectory(@"values");
NSDictionary *dic = [NSDictionary dictionaryWithObject:s forKey:key];
[dic writeToFile:file atomically:YES];

好的,pathInAppDirectory如下所示:

NSString *pathInAppDirectory(NSString *fileName)
{
    NSArray *documentDirectories = NSSearchPathForDirectoriesInDomains(NSApplicationDirectory, NSUserDomainMask, YES); 

    NSString *appDir = [documentDirectories objectAtIndex:0];
    return [appDir stringByAppendingPathComponent:fileName];
}

什么都没有发生:如果我想在稍后查看文件并想要显示值,则返回null。看一下iPhone模拟器的文件夹也会显示一个空文件夹。那里发生了什么,或者更具体地说:什么不发生?

1 个答案:

答案 0 :(得分:0)

您需要使用NSDocumentDirectory代替NSApplicationDirectory。无法在Application bundle中编写。

清理示例:

- (NSString *)pathInAppDirectory:(NSString *)fileName {
    NSArray *documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 

    NSString *appDir = [documentDirectories objectAtIndex:0];
    return [appDir stringByAppendingPathComponent:fileName];
}

    NSString *s = @"123456";
    NSString *key = @"key";
    NSDictionary *dic = [NSDictionary dictionaryWithObject:s forKey:key];
    NSString *filePath = [self pathInAppDirectory:@"values"];
    [dic writeToFile:filePath atomically:YES];