2012-07-17 83 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的视图的子视图是一个不好的做法,应该避免。

相关问题