4

我在故事板中有一個視圖,我分配了一個名爲「MainView」的標識符。但是,如果我添加了以下面的子視圖,一切都產生了碰撞(例如按一個按鈕)ViewController被取消分配導致崩潰

MainViewController *mvc = [self.storyboard instantiateViewControllerWithIdentifier:@"MainView"]; 
      [self.view addSubview:mvc.view]; 

這是由按鍵觸發的動作:(MainViewController.h)

-(IBAction)showUsername:(id)sender{ 

    [testLabel setText:@"username"]; 

} 

和崩潰日誌:

-[MainViewController performSelector:withObject:withObject:]: message sent to deallocated instance 0x44e0810 

我使用ARC。

+0

instantiateViewControllerWithIentifier:創建一個自動釋放的對象。你必須在這裏「繼續」,並且「在不再需要時釋放它。 – 2012-02-05 18:30:45

+1

我使用ARC,所以調用'retain'不支持... – 2012-02-05 18:40:54

回答

6

處理此問題的最佳方法是使用屬性。具體方法如下:

在您的.h文件中:

#import "MainViewController.h" 

@interface MyClass : UIViewController 

@property (strong, nonatomic) MainViewController *mvc; 

@end 

在您.m文件:

#import "MyClass.h" 

@implementation MyClass 

@synthesize mvc; 

// Your code here 
- (void)yourMethodHere { 
    self.mvc = [self.storyboard instantiateViewControllerWithIdentifier:@"MainView"]; 
    [self.view addSubview:mvc.view]; 
} 
+0

我已經考慮過這樣做,但是我使用ARC,所以我不能在任何對象上調用retain。 – 2012-02-05 18:40:19

+1

劃傷我說的話......使用屬性可以避免你遇到的問題。 – 2012-02-05 18:51:31

+0

謝謝你的工作:) – 2012-02-05 18:54:48