Search code examples
iosobjective-ccocoansbundle

How to hardcode a text file into iOS app


Currently using:

NSString* path = [[NSBundle mainBundle] pathForResource:@"filename" 
                                                 ofType:@"txt"];

This only works however after I manually add the file into the application bundle.

I can use the documents directory but that's even worse.

After resetting the sim, the file goes away. How do I get it to stay?

How would I write out the file from somewhere to there? Like from a file in source? I don't want to alloc a several megabyte NSString object.


Solution

  • Credit goes to Lyle42 on freenode irc (#iphonedev):

    I wasn't aware this field even existed. By adding any file into the copy files build phase (under build phases), they persist across builds.

    Then this code:

    NSString *_filePath = [[NSBundle mainBundle] pathForResource:@"filename" ofType:@"txt"];
    
    NSLog(@"%@",_filePath);
    
    NSData *_binary = [NSData dataWithContentsOfFile:_filePath];  
    
    NSString *_fileContents = [[NSString alloc] initWithData:_binary encoding:NSUTF8StringEncoding];
    

    Works just great. (loads contents of file into an NSString).

    copy files build phase