views:

208

answers:

2

hey, I'm currently using the iPhone SDK and I'm having trouble passing an NSString through 3 views

I am able to pass an NSString between 2 view controllers but I am unable to pass it through another one. My code is as follows...

    `- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)index`Path {

 NSString *string1 = nil;

 NSDictionary *dictionary = [listOfItems objectAtIndex:indexPath.section];
 NSArray *array = [dictionary objectForKey:@"items"];
 string1 = [array objectAtIndex:indexPath.row];


 //Initialize the detail view controller and display it.
 ViewController2 *vc2 = [[ViewController2 alloc] initWithNibName:@"ViewController2" bundle:[NSBundle mainBundle]];
 vc2.string1 = string1;
 [self.navigationController pushViewController:vc2 animated:YES];
 [vc2 release];
 vc2 = nil;
}

in the "ViewController 2" implementations I am able use "string1" in the title bar by doing the following....

    - (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = string1;
 UIBarButtonItem *addButton = [[[UIBarButtonItem alloc]
           initWithImage:[UIImage imageNamed:@"icon_time.png"] 
           style:UIBarButtonItemStylePlain
           //style:UIBarButtonItemStyleBordered
           target:self
           action:@selector(goToThirdView)] autorelease];
 self.navigationItem.rightBarButtonItem = addButton;

    }

but I also have a NavBar Button on the right side that I would like to push a new view

- (void)goToThirdView 
    { 
     ViewController3 *vc3 = [[ViewController3 alloc] initWithNibName:@"ViewController3" bundle:[NSBundle mainBundle]];

     [self.navigationController pushViewController:NESW animated:YES];
     vc3.string1 = string1 ;
     [vc3 release];
     vc3 = nil;
}

How do I pass on that same string to the third view? (or fourth)

+1  A: 

What you have should work exceptthat you want to set the string in vc3 before you push it onto the stack to ensure it is present when the view and the nav bar draws. That is the way you have it in the vc2 that works.

However, as a matter of application design, it is poor practice to pass values directly between view controllers. Ideally, you want your view controllers to be standalone and able to function regardless of which other controller did or did not precede it. (This becomes really important when you need to resume an app back to the point where it was interrupted.) If make the view controllers interdependent your app will grow tangled and complex as it grows larger.

The best way to exchange data between views is to park the data in a universally accessible place. If it is application state information put it in user defaults or you can put in an attribute of the app delegate. If it is user data, then it should go in a dedicated data model object (which is either a singleton or accessible through the app delegate.)

TechZen
A: 

You may find code sample from a question I asked earlier.

ohho