Anders
Anders

Reputation: 729

Read/Write to plist, incorrect structure of file

I'm trying to learn how to save/load some simple model objects to a plist file.

The model object is called "Person" and has 2 string properties "Name" "Address"

I have added the following to a plist file, just to test the loading(is the structure correct?):

<plist version="1.0">
<array>
    <dict>
        <key>Name</key>
        <string>name1</string>
        <key>Address</key>
        <string>address1</string>
    </dict>

    <dict>
        <key>Name</key>
        <string>name2</string>
        <key>Address</key>
        <string>address2</string>
    </dict>
</array>
</plist>

I load like this

 -(void)load
{

    NSError *error;

    NSFileManager *fileManager = [NSFileManager defaultManager];

    if (![fileManager fileExistsAtPath: [self plistPath]]) 

    {

        NSString *bundle = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"]; //5

        [fileManager copyItemAtPath:bundle toPath: [self plistPath] error:&error]; /
    }
     NSMutableDictionary *savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile: [self  plistPath]];

     NSLog(@"%lu",(unsigned long)savedStock.count);
}

-(NSString*)plistPath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1

    NSString *documentsDirectory = [paths objectAtIndex:0]; 

    return [documentsDirectory stringByAppendingPathComponent:@"data.plist"]; 
}

But how do i get the array that encapsulates the dictionaries that contains my actual data?

Upvotes: 0

Views: 42

Answers (1)

gabbler
gabbler

Reputation: 13766

The plist you saved is a NSArray, so you should get it back as a NSArray like this.

NSArray *savedArray = [NSArray arrayWithContentsOfFile:[self  plistPath]];

Upvotes: 2

Related Questions