2014-07-25 96 views
0

我有RootViewController的的子視圖,並呼籲時,按鍵不能被它壓而不會出現錯誤:無法按下按鈕的子視圖

Thread 1: EXC_BAD_ACCESS 

這裏是重要的代碼:

的AppDelegate:

MainViewController *MainVC = [[MainViewController alloc]init] ; 
self.window.rootViewController = mainVC ; 

而在MainViewController類:

OtherViewController *SomeView = [[OtherViewController alloc]init] ; 
[self.view addSubview:SomeView.view] ; 

OtherViewController xib按原樣加載(執行viewDidLoad的東西)。但是,當我嘗試按模擬器中的某個按鈕(在OtherViewController上)時,出現上述錯誤。

而且按鈕的代碼:

IBOutlet UIImageView *Image; //in OtherViewController.h 

//in OtherViewController.m 
- (IBAction)Button:(id)sender { 
Image.center = CGPointMake(Image.center.x + 1, Image.center.y) ; 
} 

有斷點整個OtherViewController.h和.M(到處做的按鈕)。沒有被觸發。程序中斷並在AppDelegate中給出錯誤:return UIApplicationMain(argc,argv,nil,NSStringFromClass([AppDelegate class]));

我是不是正確設置第二個視圖以使其功能完整?我該如何擺脫我的程序這個錯誤?

+0

什麼按鈕上的目標? –

+0

不,如果你創建了一個按鈕,那麼可以是附加一個'IBAction',或者有一個'[button addTarget:action:forControlEvents:]'調用將選擇器附加到按鈕上。 –

+0

你能在該IBAction中發佈代碼嗎? –

回答

2

您的問題是您在MainViewController中創建OtherViewController的一次性實例。在範圍的最後,ARC發佈OtherViewController的實例。

這裏是您的解決方案:

在MainViewController.m

@interface MainViewController() // This is an interface extension, stick that before your @implementation MainViewController 

@property (nonatomic, strong) OtherViewContontroller *SomeView; 
@end 

在你的方法是創建OtherViewController

,替換:

OtherViewController *SomeView = [[OtherViewController alloc]init] ; 
[self.view addSubview:SomeView.view] ; 

與此:

self.SomeView = [OtherViewController new]; // <-- new is a shortcut for alloc/init. :) 
[self.view addSubview:self.SomeView.view];