Skip to content

Instantly share code, notes, and snippets.

@sukima
Created October 10, 2009 04:38
Show Gist options
  • Save sukima/206600 to your computer and use it in GitHub Desktop.
Save sukima/206600 to your computer and use it in GitHub Desktop.
How to load a plist into an NSArray
/* Original code:
NSNumber *object = [[NSNumber alloc] init];
for(int i=0; i<[array count]; i++) {
NSLog(@"Value of number loaded %@", [array objectAtIndex:i]);
object = [array objectAtIndex:i];
}
*/
#import <Foundation/Foundation.h>
int main(void) {
// using arrayWithContentsOfFile is the same but uses an autorelease.
// If we instead use initWithContentsOfFile it provides us the control
// to release immediately when we know were done (at the end of the
// method) which saves the pool from having to do it. And it saves on
// performance because were not trying to include this object in the
// draining of the pool (costly).
NSArray *array = [[NSArray alloc] initWithContentsOfFile:@"test.plist"];
// This is the correct thing if your planning to use the object you just
// allocated. Because not only is it a waste of time/resources to alloc an
// object you'll never use and if it isn't released you just leaked!
// NSNumber *object = [[NSNumber alloc] init]; // DONT DO THIS!!
NSNumber *object = nil; // Do this instead.
// initalizing a variable inside the 'for' decleration is not recommended.
// It is not compatable with the default gcc and requires a newer option
// (C99 mode) which is not fully supported in gcc. You can avoid the entire
// problem and make neater code by seperating the two as so.
int i;
for (i = 0; i < [array count]; i++)
{
// Why call two methods (each costs performance hits) to get the same
// pointer back? Instead get it once and use it through out.
object = [array objectAtIndex:i];
NSLog(@"Value of number loaded %@; Variable Type:%@", object, [object class]);
}
[array release];
return 0;
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
<real>1.234</real>
<real>5.678</real>
<integer>10</integer>
</array>
</plist>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment