2010-05-03 27 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中運行的方式。

但是,就應用程序設計而言,在視圖控制器之間直接傳遞值是很差的做法。理想情況下,你希望你的視圖控制器是獨立的,並且能夠發揮作用,而不管其他控制器在其之前還是之前沒有。 (當你需要將應用程序恢復到被中斷的位置時,這變得非常重要。)如果使視圖控制器互相依賴,隨着應用程序變得越來越大,你的應用程序將越來越糾結和複雜化。

在視圖之間交換數據的最佳方式是將數據停放在一個通用的地方。如果是應用程序狀態信息,則將其置於用戶默認值中,或者可以放入應用程序委託的屬性。如果是用戶數據,那麼它應該放在一個專用的數據模型對象中(它可以是單例模式或可以通過應用程序代理訪問)。

相關問題