2011-01-09 35 views
0

該類是UITabBarViewController的子類。 在我的init父視圖控制器文件,我有這樣的:parentViewController的值

UIBarButtonItem *button1 = [[UIBarButtonItem alloc] 
           initWithTitle:@"Button1" 
           style:UIBarButtonItemStyleBordered 
           target:self 
           action:@selector(button1:)]; 

self.navigationItem.rightBarButtonItem = button1; 

[button1 release]; 

而且方法:

-(IBAction)button1:(id)sender { 

if (self.nvc == nil) { 
    ChildViewController *vc = [[ChildViewController alloc] init]; 
    self.nvc = vc; 
    [vc release]; 
} 

[self presentModalViewController:self.nvc animated:YES]; 

我想在我的childviewcontroller類,這也是一個UITabBarViewController子類來從parentviewcontroller的價值。

我該如何做到這一點,我嘗試了幾個小時,而且我只得到一個無參考。

我想要得到的對象(這是父級中的屬性)是一個NSString。

預先感謝

回答

2

有很多方法可以做到這一點。最簡單的方法是將一個屬性添加到指向您的父視圖控制器的ChildViewController。你可以稱它爲delegate。然後該方法將如下所示:

-(IBAction)newbuilding:(id)sender { 
    if (self.nvc == nil) { 
     ChildViewController *vc = [[ChildViewController alloc] init]; 
     vc.delegate = self; 
     self.nvc = vc; 
     [vc release]; 
    } 
    [self presentModalViewController:self.nvc animated:YES]; 
} 

然後從ChildViewController實例可以訪問self.delegate.someProperty

也有辦法讓父視圖控制器沒有你自己的明確的參考(通常self.tabBarController,self.navigationController取決於上下文),但上述方法是傻瓜證明,易於理解和易於調試。

4

的乾淨的方式可能是創建一個ChildViewControllerDelegate協議父視圖控制器實施。這是iOS開發中常見的習慣用法。

@protocol ChildViewControllerDelegate 
- (NSString *)getSomeNSString; 
@end 

那麼你應該做ChildViewController有這個委託作爲一個實例變量,並通過屬性來分配現在

@property (nonatomic, assign) id<ChildViewControllerDelegate> delegate; 

從內ChildViewController你可以使用這個代理來訪問委託它的方法您情況將是ParentViewController。這將允許你檢索你想要的字符串。

[delegate getSomeNSString] 

這可能看起來像很多工作的東西簡單,但它避免了問題,存儲到其父ParentViewController從ChildViewController一個反向引用繼承。

相關問題