sf89
sf89

Reputation: 5248

File containing array containing dictionary

I have a file that contains an array of dictionaries. How can I read it back to use it as a regular array containing those dictionaries in my code?

<?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>
    <dict>
        <key>elem1</key>
        <string>Hello world</string>
        <key>elem2</key>
        <string>This is some string</string>
    </dict>
</array>
</plist>

Upvotes: 1

Views: 53

Answers (2)

user529758
user529758

Reputation:

This is quite straightforward: property lists can be parsed in one line...

NSArray *array = [NSArray arrayWithContentsOfFile:pathToPLIST];

Upvotes: 1

sf89
sf89

Reputation: 5248

This on is fairly simple actually. Thanks to H2CO3 for pointing to it. Just use the [NSArray arrayWithContentsOfFile:] method. So here's what I've got:

// Path to my file
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString  *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"my_file.out"];

// Get the array contained in the file
NSMutableArray *myArray = [NSMutableArray arrayWithContentsOfFile:filePath];

// Read the array's content
int numOfelems = [myArray count];
for (int i = 0; i < numOfelems; i++) {
    NSLog(@"Object at index %i: %@", i, [myArray objectAtIndex:i]);
}

Upvotes: 1

Related Questions