[英]iOS file writing failure
我一直在嘗試將字符串寫入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始終返回(空)。 我究竟做錯了什么?
真誠的
佐利
您沒有對該文件的寫權限。 嘗試改為寫入“文檔”文件夾。
//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);
改變以下
NSString *dir = [NSHomeDirectory() stringByAppendingPathComponent:@"mydirectory"];
至
NSString *dir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.