Saturday, July 14, 2007

Accessing bundled files in Objective-C : NSBundle class

Okay, this is something new that I learned to do recently.

Lets say you have an application that has users. You want to give users the ability to set a picture to represent their account. Well, it's easier if you just have a default picture at first and allow them to change it later. The question is, how will you access that default picture in the application bundle. 
There is a class designed especially to allow us to do this type of thing. It is called NSBundle. 

So, now, you have a user set up a new account, you now need to access that default picture within the application bundle. This is how you will utilize the NSBundle class. 
  • NSImage *defaultImage = [[NSImage alloc] initWithFile:[[NSBundle mainBundle] pathForResource:@"default_image" ofType:@"png"]];
That's all there really is to do to access a bundled file. This opens up the door to many possibilities really. You can include in data files, defaults (like an image, default settings, etc...) and not really let the user have access to it. It also makes it easy for you to distribute any necessary files, in a user friendly way, for your application to work. 

I'm going to play with this some more but I think you can also write to your bundled file (like if you have a bundled database file or something). I'll check it out over the next couple of days and post about my findings. 

Happy Coding! :-)

No comments: