iPhone : Get the file path which is within subfolder of Resource folder

后端 未结 4 546
死守一世寂寞
死守一世寂寞 2020-12-09 12:24

I am new to iPhone programming. I want to read the content of a text file located in a subfolder of the Resource folder.

The Resource folder structure is the followi

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-09 13:10

    Your "resource folder" is actually the contents of your main bundle, also know as the application bundle. You use pathForResource:ofType: or pathForResource:ofType:inDirectory: to get the full path for a resource.

    Loading the contents of a file as a string is done with the stringWithContentsOfFile:encoding:error: method for an autoreleased string of with initWithContentsOfFile:encoding:error: if you want a retained string.

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Data" 
                                                         ofType:@"txt"
                                                    inDirectory:@"Folder1"];
    if (filePath != nil) {
      theContents = [NSString stringWithContentsOfFile:filePath
                                              encoding:NSUTF8StringEncoding
                                                 error:NULL];
      // Do stuff to theContents
    }
    

    This is almost the same answer as given by Shirkrin previously, but with the slight difference that it works on target. This is because initWithContentsOfFile: is deprecated on Mac OS X, and not available at all iPhone OS.

提交回复
热议问题