0

我有一个带有单个视图的简单应用程序,上面有一个按钮。单击按钮时,它会添加第二个视图。这第二个视图有一个简单的工具栏,上面有一个UIBarButtonItem。它已注册以触发我的视图控制器的消息。

但是,只要我单击按钮,应用程序就会崩溃。启用僵尸,我看到我的视图控制器被解雇了。添加一个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,或者我使用视图/视图控制器的方式。由于视图仍然可见,对我来说,它的 viewController 不应该被释放。除了创建我自己对视图控制器的强引用之外,还有什么方法可以防止这种情况发生?

改写

是否有任何非补丁非肮脏方式让视图控制器保持分配状态,直到其视图从显示中删除。我认为从视图控制器到自身的任何指针都是脏的,尽管这是我目前使用的方式。

4

2 回答 2

0

如果您不希望 arc 立即释放它(在定义实例的范围的末尾),则必须保持对 IssueViewController 实例的强引用。

于 2012-07-17T15:57:13.947 回答
0

答案是:将视图控制器的视图添加为另一个视图控制器的视图的子视图是一种不好的做法,应该避免。

于 2012-07-18T01:25:15.890 回答