iOS文件写入失败

时间:2012-06-18 12:25:58

标签: ios ios5

我一直在尝试将字符串写入iOS5.1中的文件,但文件内容始终为(null)。你能帮我弄清楚原因吗? 这是我的代码:

NSString *dir = [NSHomeDirectory() stringByAppendingPathComponent:@"mydirectory"];

NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        NSMutableString *randomString = [NSMutableString stringWithCapacity: 64];

for (int i=0; i<DEFAULT_LENGHT_OF_NOTE_FILE_ID; i++) 
{
    [randomString appendFormat: @"%C", [letters characterAtIndex: arc4random() % [letters length]]];
 }

 NSString* randomFileName = [NSString stringWithFormat:@"%@.html",randomString];
 NSString *filePath = [dir stringByAppendingPathComponent:randomFileName];

 NSString *str = @"Mystr";

//save content to the documents directory
 [str writeToFile:filePath atomically:NO encoding:NSStringEncodingConversionAllowLossy 
                       error:nil];


 NSString *content = [[NSString alloc] initWithContentsOfFile:filePath
                                                        usedEncoding:nil
                                                               error:nil];

 NSLog(@"%@", content);

NSLog始终返回(null)。我做错了什么?

此致

佐利

2 个答案:

答案 0 :(得分:0)

您没有该文件的写入权限。请尝试写入“文档”文件夹。

//Get the documents folder
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];

...

NSString *filePath = [dir stringByAppendingPathComponent:randomFileName];
[str writeToFile:filePath atomically:NO encoding:NSStringEncodingConversionAllowLossy 
                       error:nil];

您可以随时使用writeToFile中的错误并将其打印出来以找出错误。

NSError *error = nil;
[str writeToFile:filePath atomically:NO encoding:NSStringEncodingConversionAllowLossy 
                       error:&error];
if(error) NSLog(@"Error:%@" error.localizedDescription);

答案 1 :(得分:0)

更改以下内容

NSString *dir = [NSHomeDirectory() stringByAppendingPathComponent:@"mydirectory"];

NSString *dir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];