我有一个带有单个视图的简单应用程序,上面有一个按钮。单击按钮时,它会添加第二个视图。这第二个视图有一个简单的工具栏,上面有一个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 不应该被释放。除了创建我自己对视图控制器的强引用之外,还有什么方法可以防止这种情况发生?
改写
是否有任何非补丁非肮脏方式让视图控制器保持分配状态,直到其视图从显示中删除。我认为从视图控制器到自身的任何指针都是脏的,尽管这是我目前使用的方式。