Objective C - 加载文件的内容但显示为null

时间:2014-05-16 13:07:52

标签: ios objective-c

我在Document目录中创建了一个文本文件。然后我在下面编写了这段代码来加载它的内容。

NSURL *path = [[NSFileManager defaultManager]
                       URLForDirectory:NSDocumentDirectory
                       inDomain:NSUserDomainMask
                       appropriateForURL:nil
                       create:NO
                       error:nil];

NSURL *fullPath = [path URLByAppendingPathComponent:@"text.txt"];
NSLog(@"URL of text file is : %@", fullPath);
NSString *content = [[NSString alloc] initWithContentsOfURL:fullPath encoding:NSUTF8StringEncoding error:nil];
NSLog(@"Load the content of Text file : %@", content);

我得到null这样的结果:

2014-05-16 19:53:01.198 LoadStringContent[407:303] URL of text file is : file:///Users/Visal/Documents/text.txt
2014-05-16 19:53:01.199 LoadStringContent[407:303] Load the content of Text file : (null)

任何人都有任何想法纠正它!请帮忙!

感谢!

1 个答案:

答案 0 :(得分:0)

更改

NSString *content = [[NSString alloc] initWithContentsOfURL:fullPath encoding:NSUTF8StringEncoding error:nil];

NSError *error = nil;
NSString *content = [[NSString alloc] initWithContentsOfURL:fullPath encoding:NSUTF8StringEncoding error:&error];
NSLog(@"error: %@", error);

结束检查错误结果。