1

我一直在尝试将字符串写入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)。我究竟做错了什么?

真挚地,

佐利

4

2 回答 2

0

您没有对该文件的写入权限。请尝试写入您的 Documents 文件夹。

//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);
于 2012-06-18T12:28:14.780 回答
0

更改以下内容

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

NSString *dir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
于 2012-06-18T12:29:44.953 回答