views:

44

answers:

1

I've got a problem that I think is probably straight forward but I can't seem to wrap my head around it.

I've got a tableview that loads from an array of NSDictionaries. Each Dictionary has a title (shown in the row) and an associated nssstring representing a viewcontroller that should be pushed onto the stack when the row is selected. In other words, selecting row "A" needs to initialize an instance of "aViewController" and push it on the stack, selecting row "B" needs to initialize an instance of "bViewController" and push it on the stack, etc.

I originally just hardcoded all possible values into didSelectRow. But I'd really like to be able to dynamically generate the viewController dynamically. I found a few C++ examples of similar problems that led me to the code below. But I can't seem to get it right and am not sure I'm on the right track for an objective-c solution. Anyone have any thoughts?

Here's the didSelectRow code that's not working:

Class cls = [selectedRow valueForKey:@"viewController"]; 
if (cls!= nil)
{
id myNewController = [[cls alloc] init];    
}


[[self navigationController] pushViewController:myNewController animated:YES];
[myController release];
+4  A: 

Are you storing the actual Class or the class name (as an NSString) in the dictionary?

If the value you are storing in the dictionary is an NSString I don't think you can just assign Class cls = someNSString;

You can, however, do:

NSString *controllerClassName = [selectedRow valueForKey:@"viewController"];
if (controllerClassName != nil) {
     id myNewController = [[NSClassFromString(controllerClassName) alloc] init];
     [[self navigationController] pushViewController:myNewController animated:YES];
     [myNewController release];
}

OR

Just store the Class in the dictionary instead of the NSString representation:

George
"NSClassFromString". So obvious, so intuitive, and yet when you're clueless, so hard to find. Thanks for helping!
Martin