Challenge solution: NSMutableDictionary as plist container


#1

I checked out the Apple documentation and it appears that NSMutableArray is anything but the sole class that is able to contain a preference list. So I opted to solve the challenge using an NSMutableDictionary instead of an NSMutableArray as container. Please feel free to suggest improvements/corrections/optimizations!

[code]//
// main.m
// PropertyList
//
// Created by YR on 08/02/12.
// Copyright © 2012 YR. All rights reserved.
//

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{

@autoreleasepool {
    
    // In this example, the plist container is an NSDictionary object.
    NSMutableDictionary *rootList = [[NSMutableDictionary alloc] init ];
    
    // NSDictionary
    NSMutableDictionary *dc = [[NSMutableDictionary alloc] init];        
    [dc setObject:@"Joe" forKey:@"first_name"];
    [dc setObject:@"Doe" forKey:@"last_name"];
    
    // NSString
    NSString *s = [NSString stringWithFormat:@"Read my lips.\n"];
    
    // NSData (a png file I have placed in /tmp)
    NSData *dt = [NSData dataWithContentsOfFile:@"/tmp/classicplus.png"];
    
    // NSDate
    NSDate *d = [NSDate dateWithTimeIntervalSinceNow:0.0];
    
    // Integer (NSNumber)
    NSNumber *i = [NSNumber numberWithInt:100];
    
    // Float (NSNumber)
    NSNumber *f = [NSNumber numberWithFloat:M_PI];
    
    // Boolean
    NSNumber *b = [NSNumber numberWithBool:[i isLessThanOrEqualTo:f]];
    
    // Array
    NSArray *a = [NSArray arrayWithObjects:@"Object 1", @"Object 2", @"Object 3", nil];
    
    // Create preference list
    [rootList setObject:dc forKey:@"dictionary"];
    [rootList setObject:s forKey:@"string"];
    [rootList setObject:dt forKey:@"data"];
    [rootList setObject:d forKey:@"date"];
    [rootList setObject:i forKey:@"integer"];
    [rootList setObject:f forKey:@"float"];
    [rootList setObject:b forKey:@"boolean"];
    [rootList setObject:a forKey:@"array"];
    
    // Flush list to disk as plist file
    [rootList writeToFile:@"/tmp/my.plist" atomically:YES];
    
    // Finally, load the plist from disk and display its contents on screen
    NSDictionary *myplist = [NSDictionary dictionaryWithContentsOfFile:@"/tmp/my.plist"];

    for (NSString *nextEntry in myplist) {
        NSLog(@"\nType: %@\nContents:%@\n\n", nextEntry, [myplist objectForKey:nextEntry]);
    }
}

return 0;

}
[/code]