AlwynIsPat
AlwynIsPat

Reputation: 739

Read & write my Plist that has an Array of Dictionary using Xcode

here's my issue, i'm trying to create a UITableView that is able to display the Names in my plist into the cells. I can't get the names out of the Plist. guess i'm not very certain with the programming codes required to extract the info.

if you could help by providing a good tutorial or sample codes would be wonderful. Thanks!

<array>
    <dict>
        <key>Name</key>
        <string>Device 2</string>
    </dict>
    <dict>
        <key>Name</key>
        <string>Device 1</string>
    </dict>
</array>

These codes are in my viewDidLoad..

NSBundle *bundle = [NSBundle mainBundle];

    NSString *path = [bundle pathForResource:@"devicelist" ofType:@"plist"];

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

    contentDict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
    NSLog(@"The count: %i", [contentDict count]);
    contentArray = [NSMutableArray arrayWithContentsOfFile:path];
    NSLog(@"The array: %i", [contentArray count]);
    [contentArray retain];
    [contentDict retain];
    [mainTableView reloadData];

and these in my tableView..

static NSString *MyIdentifier = @"MyIdentifier";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier]autorelease];
    }

    cell.textLabel.text = [sortedArray objectForKey:indexPath.row];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;

Upvotes: 1

Views: 5887

Answers (1)

indiantroy
indiantroy

Reputation: 1503

Maybe you wanna try out the below in viewDidLoad:

NSBundle *bundle = [NSBundle mainBundle];

    NSString *path = [bundle pathForResource:@"devicelist" ofType:@"plist"];

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

    self.contentArray = [NSMutableArray arrayWithContentsOfFile:path];
    NSLog(@"The array: %i", [contentArray count]);

    [mainTableView reloadData];
}

just notice that contentArray should be a retain property and then in cellForRowAtIndexPath method:

NSDictionary *dict = [self.contentArray objectAtIndex:indexPath.row];
cell.textLabel.text = (NSString*)[dict objectForKey:@"Name"];

Hope this helps...

Upvotes: 4

Related Questions