ShurupuS
ShurupuS

Reputation: 2923

pathForResource is empty in iOS

Can't understand, why does this line of the code return (null)?

// Get path of data.plist file to be created

plistPath = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"];

I need to create new plist but can't understand, does the empty file should be created before to get the path to it.. Any ideas?

PS I had only h,m and no plist files in my project now.

Upvotes: 1

Views: 413

Answers (2)

user2000809
user2000809

Reputation: 496

Yes, your guess was right - you would need to create a file first. Here is what the class reference documentation had to say about the method's return value

"Return Value The full pathname for the resource file or nil if the file could not be located."

You could do something like:

if ( [ [NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"] )
    plistPath = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"];
else
    // Create new file here

Also, you could leave out the type extenxion in the method call above if you are searching for a unique file name.

Source: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSBundle_Class/Reference/Reference.html

Upvotes: -2

DrummerB
DrummerB

Reputation: 40221

You don't create new files in your bundle after deployment. The bundle contains all the resources and files that ship with your app.

Instead, you create new files in your app's Documents folder. To get the documents folder path, you can use a method like this (as included in some of the app template projects):

- (NSString *)applicationDocumentsDirectory {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    return basePath;
}

Then you simply append the file name you want to use.

NSString *path = [self applicationDocumentsDirectory];
path = [path stringByAppendingPathComponent:@"data.plist"];

You might also want to have some additional folders in your Documents folder for organizational purposes. You can use NSFileManager to do that.

Upvotes: 7

Related Questions