【问题标题】:contentOfFile path gives nullcontentOfFile 路径给出 null
【发布时间】:2012-04-02 15:37:41
【问题描述】:

我正在尝试将 txt 文件中的所有文本转换为字符串,但如果我尝试 NSlog() 这个字符串,我会得到空值。我认为这是因为我试图获取文件的路径,但我似乎无法弄清楚路径有什么问题。我知道我得到了正确的 navigationItem.title,所以这不是问题。文本文件位于主包中名为 Øvelser/Text/"nameOfExercise".txt 的子文件夹中。我在下面粘贴了我的代码:

- (void)viewDidLoad
{
[super viewDidLoad];

//Read from the exercise document
NSString *path = [[@"Øvelser/Text/" stringByAppendingString:self.navigationItem.title] stringByAppendingString:@".txt"];

if(path)
{

    _exerciseDocument = [NSString stringWithContentsOfFile:path encoding: NSUTF8StringEncoding error:nil];
    NSLog(@"%@", _exerciseDocument);
}
else 
{
    NSLog(@"error");
}
}

【问题讨论】:

    标签: objective-c ios5 xcode4.2 filepath


    【解决方案1】:

    您需要使用NSBundle 方法来获取相对于包的路径。这个question 是类似的,并以此作为创建路径的一种方式:

    NSBundle *thisBundle = [NSBundle bundleForClass:[self class]];
    NSString *filePath = nil;
    
    if (filePath = [thisBundle pathForResource:@"Data" ofType:@"txt" inDirectory:@"Folder1"])  {
    
        theContents = [[NSString alloc] initWithContentsOfFile:filePath];
    
        // when completed, it is the developer's responsibility to release theContents
    

    【讨论】:

      【解决方案2】:

      你得到 nil 是因为读取文件出了问题。如果你传递一个指向错误对象的指针,它将被填充错误详细信息,如果你记录它,它将告诉你出了什么问题。不要忽略错误信息。

      NSError* error = nil;
       _exerciseDocument = [NSString stringWithContentsOfFile: path 
                                                     encoding: NSUTF8StringEncoding  
                                                        error: &error];
      if (_exerciseDocument == nil)
      {
           NSLog(@"Error: %@", error);
      }
      else
      {
           // success
      } 
      

      NSString 有很多可爱的方法来操作路径,你应该使用它们。特别是使用stringByAppendingPAthComponentsstringByAppendingPathExtension 构建您的路径。

      【讨论】:

        猜你喜欢
        • 2015-06-05
        • 2015-01-21
        • 1970-01-01
        • 1970-01-01
        • 2018-10-12
        • 2011-01-11
        • 2017-12-28
        • 1970-01-01
        • 2022-07-26
        相关资源
        最近更新 更多