2010-05-03 65 views
0

嘿,我目前正在使用iPhone SDK,并且在通过3个视图传递NSString时遇到问题如何通过3个ViewControllers传递一个NSString?

我能够在2个视图控制器之间传递NSString,但我无法将其传递给另一个视图控制器。我的代码如下...

`- (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; 
} 
在“视图控制器2”实现

我通过执行以下操作....

- (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; 

    } 

但我在标题栏可以使用“字符串1”也有一个NavBar按钮在右侧,我想推新视图

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

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

如何将同一字符串传递到第三个视图? (或第四个)

回答

0

您可能会发现前面提到的question的代码示例。

1

除了在vc3中将字符串压入堆栈之前,确保它在视图和导航栏绘制时存在之外,您应该有哪些工作。这是你在vc2中运行的方式。

但是,就应用程序设计而言,在视图控制器之间直接传递值是很差的做法。理想情况下,你希望你的视图控制器是独立的,并且能够发挥作用,而不管其他控制器在其之前还是之前没有。 (当你需要将应用程序恢复到被中断的位置时,这变得非常重要。)如果使视图控制器互相依赖,随着应用程序变得越来越大,你的应用程序将越来越纠结和复杂化。

在视图之间交换数据的最佳方式是将数据停放在一个通用的地方。如果是应用程序状态信息,则将其置于用户默认值中,或者可以放入应用程序委托的属性。如果是用户数据,那么它应该放在一个专用的数据模型对象中(它可以是单例模式或可以通过应用程序代理访问)。

相关问题