Friday, May 31, 2013

NSArray arrayWithContentsOfFile example in Objective C (iOS).


NSArray arrayWithContentsOfFile


Creates and returns an array containing the contents of the file specified by a given path.

+ (id)arrayWithContentsOfFile:(NSString *)aPath

Parameters
aPath
The path to a file containing a string representation of an array produced by the writeToFile:atomically: method.

Return Value of [NSArray arrayWithContentsOfFile]
An array containing the contents of the file specified by aPath. Returns nil if the file can’t be opened or if the contents of the file can’t be parsed into an array.

Discussion of [NSArray arrayWithContentsOfFile]
The array representation in the file identified by aPath must contain only property list objects (NSString, NSData, NSDate, NSNumber, NSArray, or NSDictionary objects). For more details, see Property List Programming Guide. The objects contained by this array are immutable, even if the array is mutable.

NSArray arrayWithContentsOfFile example.
+(NSMutableArray*) arrayFromPlist{
    NSLog(@"Loading array of plant types from plist.");

    NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString* filePath    = [rootPath stringByAppendingPathComponent:@"PlantTypes.plist"];
    NSFileManager*  fileManager = [NSFileManager defaultManager];

    if([fileManager fileExistsAtPath:filePath]){
        NSLog(@"Plist file exists at expected location.");
        NSMutableArray* plant_dicts = [NSMutableArray arrayWithContentsOfFile:filePath];
        NSLog(@"Loaded array with contents of file, got %d plant types.", plant_dicts.count);
        NSMutableArray* plant_types = [NSMutableArray arrayWithCapacity: plant_dicts.count];
        for(int i = 0; i< plant_dicts.count; i++){
            NSMutableDictionary* dict = [plant_dicts objectAtIndex: i];
            [plant_types addObject: dict];
        }
        return plant_types;
    }
    NSLog(@"Plant Type plist file not found.");
    return NULL;
}

Example of [NSArray arrayWithContentsOfFile].
NSString *file = [[NSBundle mainBundle] pathForResource:@"appFeatures" ofType:@"plist"];
_arrFeats = [NSArray arrayWithContentsOfFile:file];
NSLog(@"%i", _arrFeats.count);

NSArray arrayWithContentsOfFile example.
NSArray *paths =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;

NSString *plistName = @"league";
NSString *finalPath = [basePath stringByAppendingPathComponent:
                       [NSString stringWithFormat: @"%@.plist", plistName]];


contentArray = [NSArray arrayWithContentsOfFile:finalPath];

End of NSArray arrayWithContentsOfFile example article.