views:

336

answers:

2

I have an iPhone app with a tableviewcontroller. When you click a certain cell it opens a new uiviewcontroller with this code:

 nextViewController = [[avTouchViewController alloc] initWithNibName:@"avTouchViewController" bundle:nil];

The uiviewcontroller above called avTouchViewController has a property that looks like:

IBOutlet SomeObject *controller;

SomeObject is an object with all relevant view properties.

I would like to pass an nsstring parameter from the tableviewcontroller I initialize the avTouchViewController with to someObject.

How can I do this?

+1  A: 

I'm a little confused by your question; you say you're creating your avTouchViewControllers when a cell is tapped inside an existing UITableView, but your last part describes the inverse situation.

Basically, if you want to pass information to a view controller, just give it a property that can be set (which may already be the case), e.g.:

nextViewController = [[avTouchViewController alloc] initWithNibName:@"avTouchViewController" bundle:nil];
nextViewController.controller = theInstanceOfSomeObjectIWantToPass;

You also may want to rename your controller property. To a reader, it doesn't make sense that a view controller has a property called controller which is actually a SomeObject*. As well, your class names should be capitalized, i.e. use AvTouchViewController instead of avTouchViewController.

Shaggy Frog
A: 

If I were doing this I would add my own initializer to my UIViewController subclass:

- (id)initWithController:(NSString *pController) {
    if (self = [super initWithNibName:@"avTouchViewController" bundle:nil]) {
        self.controller = pController;
    }
    return self;
}

And then just call the following (in tableView:didSelectRowAtIndexPath: or whereever):

NSString *controller = @"Sample String";

AVTouchViewController *nextViewController = [[AVTouchViewController alloc] initWithController:controller];
[controller release];

[self.navigationController pushModalViewController:nextViewController animated:YES];
[nextViewController release];

As a point of style, class names conventionally begin with uppercase letters (hence my change to AVTouchViewController).

Frank Schmitt
I used to prefer this method myself (coming from a strong C++ background and not liking the Cocoa requirement for all classes to have default constructors), but I stopped using it a few months ago. I think it's better that Cocoa code read more like a Cocoa developer would expect. That includes using default inits, and using parameters to set values.
Shaggy Frog