2012-07-17 88 views
0

我有一個簡單的應用程序與單個視圖,它上面有一個按鈕。點擊按鈕時,它會添加第二個視圖。這第二個視圖有一個簡單的工具欄,上面有一個UIBarButtonItem。它被註冊以激發我的視圖控制器的消息。ARC釋放我的視圖控制器視圖是可見的

但是,只要我點擊按鈕,應用程序崩潰。啓用殭屍,我看到我的視圖控制器被解僱。添加一個dealloc函數,通過調用NSLog(),我發現只要我的視圖可見,我的視圖控制器就會被解散!

也沒有像shouldAutorotateToInterfaceOrientation這樣的消息被觸發。

我的視圖控制器的.h:

#import <UIKit/UIKit.h> 

@interface IssueViewController : UIViewController 
{ 
    IBOutlet UIBarButtonItem *button; 
} 

@property (nonatomic, readonly) UIBarButtonItem *button; 

- (IBAction)buttonTapped:(id)sender; 

+ (void)showSelfInView:(UIView *)view; 

@end 

其.M:

#import "IssueViewController.h" 

@interface IssueViewController() 

@end 

@implementation IssueViewController 

@synthesize button; 

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) { 
     // Custom initialization 
    } 
    return self; 
} 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view from its nib. 
    self.button.target = self; 
    self.button.action = @selector(buttonTapped:); 

} 

- (void)viewDidUnload 
{ 
    NSLog(@"unloaded"); 
    [super viewDidUnload]; 
    // Release any retained subviews of the main view. 
    // e.g. self.myOutlet = nil; 
} 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{ 
    return (interfaceOrientation == UIInterfaceOrientationPortrait); 
} 

- (void)dealloc 
{ 
    NSLog(@"Got dealloc"); 
} 

+ (void)showSelfInView:(UIView *)view 
{ 
    IssueViewController *ivc = [[IssueViewController alloc] init]; 
    [view addSubview:ivc.view]; 
} 

- (IBAction)buttonTapped:(id)sender 
{ 
    [self.view removeFromSuperview]; 
} 


@end 

代碼用來觸發第二視圖的顯示:

[IssueViewController showSelfInView:self.view]; 

任何人都知道我是什麼做錯了?爲什麼我的UIViewController至少保留到視圖被刪除?

編輯

我知道ARC,強&弱引用...在非ARC-代碼,在showSelfInView:我會保留視圖控制器,我會自動釋放它buttonTapped

對我來說,這是一個可行的方法。我想知道是否我錯過了ARC的一些東西,或者我使用view/viewController的方式。由於視圖仍然可見,對我來說,它的viewController不應該被解除分配。除了創建我自己強烈的視圖控制器引用外,是否有任何方法可以防止這種情況發生?

改寫

是否有任何非片狀非骯髒的方式有保持分配直到其觀點被取消顯示視圖控制器。我認爲從視圖控制器到它自己的任何指針都很髒,儘管這是我目前使用的方式。

回答

0

如果您不想讓arc立即釋放它(在定義該實例的作用域的末尾),您必須保持對IssueViewController實例的強引用。

+0

是的,我知道,現在我有一個醜陋的補丁:類似於:@property(nonatomic,strong)IssueViewController * mySelf',它是在viewDidLoad中初始化的,我在'buttonTapped'中設置爲nil。這工作正常,但我決定問這個問題,因爲我認爲它必須是一個不那麼醜陋的方式來實現它:) – user1532080 2012-07-17 20:31:13

0

答案是:添加一個viewcontroller的視圖作爲另一個viewcontroller的視圖的子視圖是一個不好的做法,應該避免。

相關問題