Feb 012013
 

Years ago I was learning Java on the job and my co-worker Scott mentioned reflection to me. I had never heard of it, it was wild stuff and I could see that someday it could really come in handy again. Well it has.

I had a UI I had to build for my iOS app. It was just a vertical menu that was implemented as group of UITableViewCells. I had built an array of them to populate the table, that was easy.

   self.actionArray = @[
        @"Unicorns",
        @"Ponies",
        @"Settings",
        @"Privacy Policy",
        @"About",
    ];

And I wrote the usual UITableViewDelegate code to populate the table from that array. But how could I create the view controllers? It was easy to add them to the array;

   self.actionArray = @[
        @[ @"Unicorns", @"UnicornsViewController"],
        @[ @"Ponies", @"PoniesViewController"],
        @[ @"Settings", @"SettingsViewController"],
        @[ @"Privacy Policy", @"PrivacyViewController"],
        @[ @"About", @"AboutViewController"],
    ];

Then I remember that bit that Scott taught me, reflection. I had the class name, surely I could do something with it. And I could:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Class vcClass = NSClassFromString ([[actionArray_ objectAtIndex:[indexPath row]] objectAtIndex:1]);

    UIViewController *detailViewController = [[vcClass alloc] initWithNibName:[[actionArray_ objectAtIndex:[indexPath row]] objectAtIndex:1] bundle:nil];

    [self.navigationController pushViewController:detailViewController animated:YES];
}

When you tapped a cell the view controller’s name was extracted from the array. I got a class object for it, alloced one of those and inited with the nib of the same name.