Thursday, May 9, 2013

NSDictionary initWithContentsOfFile example ios


initWithContentsOfFile:

Initializes a newly allocated dictionary using the keys and values found in a file at a given path.
- (id)initWithContentsOfFile:(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 initWithContentsOfFile]
An initialized dictionary—which might be different than the original receiver—that contains the dictionary atpath, 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 initWithContentsOfFile]
The dictionary representation in the file identified by path must contain only property list objects (NSString,NSDataNSDateNSNumberNSArray, 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 initWithContentsOfFile]
NSString *path = [[NSBundle mainBundle] pathForResource:@"DataBase" ofType:@"plist"];
NSDictionary *rootDict = [[NSDictionary alloc] initWithContentsOfFile:path];
NSString *URLString = [[rootDict objectForKey:key] objectForKey:@"URL"];
[[URLString retain] autorelease];
[rootDict release];
if ( !URLString ) {
    URLString = @"";
}
Example of [NSDictionary initWithContentsOfFile]
NSString *path = [[NSBundle mainBundle] pathForResource:@"DataBase" ofType:@"plist"];
NSDictionary *rootDict = [[NSDictionary alloc] initWithContentsOfFile:path];
NSString *URLforAll = @"";
for (id key in rootDict) {
        if ( [key isEqualToString:rowString] ) {
                NSDictionary *dict = [rootDict objectForKey:key];
                URLforAll = [dict objectForKey:@"URL"];
        }
}
[[URLforAll retain] autorelease];
[rootDict release];
Example of [NSDictionary initWithContentsOfFile]
NSString *path = [[NSBundle mainBundle] pathForResource:@"stateInfo" ofType:@"plist"];

NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:path]) {
    NSLog(@"The file exists");
} else {
    NSLog(@"The file does not exist");
}

NSMutableDictionary *myDic = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
//NSDictionary *myDic = [NSDictionary dictionaryWithContentsOfFile:path];
NSLog(@"The count: %i", [myDic count]);

NSArray *thisArray = [[NSArray alloc] initWithContentsOfFile:path];
NSLog(@"The array count: %i", [thisArray count]);