Kri*_*son 12 cocoa-touch objective-c
使用NSString读取文本文件:stringWithContentsOfFile?
NSString *txtFilePath = [[NSBundle mainBundle] pathForResource:@"\help" ofType:@"txt"];
NSString *txtFileContents = [NSString stringWithContentsOfFile:txtFilePath encoding:NSUTF8StringEncoding error:NULL];
NSLog(@"File: %@",txtFileContents);
Run Code Online (Sandbox Code Playgroud)
结果我得到"null".我如何知道要指定的路径?
谢谢
(我把文件放在"组和文件"下...所以不确定我是否需要指定路径或只是文件名.也许还有其他错误???
hig*_*ted 13
我认为你道路上的反斜杠让人感到困惑.试试这个:
NSString *txtFilePath = [[NSBundle mainBundle] pathForResource:@"/help" ofType:@"txt"];
Run Code Online (Sandbox Code Playgroud)
此外,如评论中所述,您需要使用项目的构建阶段来复制"help.txt"文件.
试试这个.您想要的是路径,help.txt但您必须将其拆分为其工作方法的名称和扩展名.
NSString *txtFilePath = [[NSBundle mainBundle] pathForResource: @"help" ofType: @"txt"];
Run Code Online (Sandbox Code Playgroud)
指定NULL而不是nil错误参数也没有坏处.这是因为nil表示对象而NULL表示指针.