Pass string from tableviewcontroller to viewcontro

2019-08-23 11:46发布

问题:

How should I pass a string to the view controller that gets pushed when a tableviewcell is selected. Should I create a custom init method in the view controller? eg [[myvc alloc]initWithURL:...] Set a property? eg [myvc setURL:...] or myvc.url = ... or just create a custom method? [myvc setLoadingURL:...]

回答1:

We've actually done this both ways (with an init and a property). I found the property the best method because the custom init method may not be called if the ViewController is created by InterfaceBuilder. With the property, you are always forced to set it if you desire to use it.

Just $0.02,
-dan



回答2:

Any of those solutions would be acceptable. I think if you're just passing it one string, that a property would be sufficient. I've been saving init methods for more complex objects. Here's one I did recently for a "high scores" table that when you tapped a row, showed a profile view on the stack:

ProfileController *profileController = [[ProfileController alloc] initWithNibName:@"ProfileController" bundle:nil];
// pass the controller the player object
[profileController showProfile:player];
// show it by pusing it on the stack
[self pushViewController:profileController animated:YES];
[profileController release];

I could create another initializer like

ProfileController *profileController = [[ProfileController alloc] initWithPlayer:player];

instead. That is a little bit more elegant looking, but as I said, any of your approaches would be fine.