Thursday, October 1, 2009

Loading data from the main bundle

I'm going to do another post or two exploring table views and bindings. But first, here is a simple example of how to load some fake data to your application for use when you're just starting on the design.

Let's first construct a plist file with some fake data. The easiest way to do this is with a text editor. If you make a new project (Cocoa application), open the file YourAppName-Info.plist with a text editor, and copy the header into a new file. It should look something like this, depending on the window size:



Type the following data in below it and save the file (text format) as fakeData.plist.



(I would paste the text here, but all the "<" symbols screws up the html). Copy the file into the project folder, then from XCode add the file to the project. Make sure it is in the Resources folder. Now, run the following function from an appropriate place, like the AppDelegate.

- (void)loadFakeData {
NSBundle *bundle = [NSBundle mainBundle];
NSString *fn = [bundle
pathForResource:@"fakeData"
ofType:@"plist"];
NSURL *fileURL = [NSURL fileURLWithPath:fn];
[self setDataArray:[NSMutableArray
arrayWithContentsOfURL:fileURL]];
NSLog(@"dataArray %@",
dataArray);
}


In the console, you should see this (logging info snipped out):

DataModel init 
dataArray (
{
amount = 100;
clear = 0;
name = dep;
},
{
amount = "10.39999961853027";
checkNumber = 1;
clear = 0;
name = x;
}
)


[UPDATE: I forgot to put up the header for the file and a few other details. Sorry. See the next post.]

No comments: