Tuesday, May 7, 2013

NSDictionary dictionaryWithContentsOfFile example ios


dictionaryWithContentsOfFile:

Creates and returns a dictionary using the keys and values found in a file specified by a given path.
+ (id)dictionaryWithContentsOfFile:(NSString *)path
Parameters
path
A full or relative pathname. The file identified by path must contain a string representation of a property list whose root object is a dictionary.
Return Value of [NSDictionary dictionaryWithContentsOfFile]
A new dictionary that contains the dictionary at path, or nil if there is a file error or if the contents of the file are an invalid representation of a dictionary.
Discussion of [NSDictionary dictionaryWithContentsOfFile]
The dictionary representation in the file identified by path must contain only property list objects (NSStringNSDataNSDateNSNumberNSArray, or NSDictionary objects). For more details, see Property List Programming Guide. The objects contained by this dictionary are immutable, even if the dictionary is mutable.
Example of [NSDictionary dictionaryWithContentsOfFile]
NSDictionary* mydictionary = [ NSDictionary dictionaryWithContentsOfFile:[ [ [ NSBundle      mainBundle] bundlePath ] stringByAppendingPathComponent:@"MyLevels.plist" ] ];

NSMutableArray *panelNames1;                                                         
panelNames1 = [[NSMutableArray alloc] init];

for (id theKey in mydictionary) {        
    [panelNames1 addObject:[mydictionary objectForKey:theKey]]; 
}
Example of [NSDictionary dictionaryWithContentsOfFile]
NSMutableArray *mutableArray =[[NSMutableArray alloc] initWithObjects:nil];
NSDictionary *mainDictionary = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"animals" ofType:@"plist"]];

   //--get parent dictionary/Array named animals which holds the animals dictionary items
    NSDictionary *parentDictionary = [mainDictionary objectForKey:@"animals"];


    //---enumerate through the dictionary objects inside the parentDictionary
    NSEnumerator *enumerator = [parentDictionary objectEnumerator];
    id value;

    while ((value = [enumerator nextObject])) {
        if ([[value valueForKey:@"minAge"] isEqualToNumber:[NSNumber numberWithInt:3]]) 
        {            

            [mutableArray addObject:[value valueForKey:@"name"]];                  
        }


    }