[Objective-C]UIViewController 挡在ARC

发布时间: 2016/9/21 4:53:15
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我有一个子类-MyPopUpViewController > UIViewController

@protocol MyPopUpViewController Delegate;
@interface MyPopUpViewController : UIViewController
{

}
@property (nonatomic, strong) id <MyPopUpViewControllerDelegate>  delegate;

-(IBAction) buttonPressed:(id)sender;
@end

@protocol MyPopUpViewControllerDelegate
-(void) popupButtonPressed: (MyPopUpViewController*)controller;
@end

因为这来自外部,可能有很多和这些弹出窗口的倍数可以了,我不能让这 MyPopUpViewController 为一个实例变量。 到目前为止,我尝试过了,和它的崩溃对委托电话,由于不会保留︰

MyMainViewController:

-(void)externalNotificationReceived: (NSString*) sentMessage
{    
    MyPopUpViewController *popupView = [[MyPopUpViewController alloc] init];
    popupView.delegate = self;

    [self.view addSubview:popupView.view];

    [popupView setInfo :sentMessage :@"View" :@"Okay"];
    popupView.view.frame = CGRectMake(0, -568, 320, 568);
    popupView.view.center = self.view.center;
}

-(void)popupButtonPressed:(MyPopUpViewController *)controller :(int)sentButtonNumber
{
    NSLog(@"Popup Delegate Called");

    [controller.view removeFromSuperview];
    controller.delegate = nil;
    controller = nil;
}

一旦弹出窗口出现,并点击确定按钮,它崩溃,永远不会到达那 NSLog。 如何更改

MyPopUpViewController * popupView = [[MyPopUpViewController 分配] init];

..所以它将保留而不使其实例变量?

在此先感谢。

解决方法 1:

你应该做适当的视图控制器遏制通过调用 addChildViewController:

- (void)externalNotificationReceived: (NSString*) sentMessage {    
    MyPopUpViewController *popupView = [[MyPopUpViewController alloc] init];
    popupView.delegate = self;

    [popupView setInfo :sentMessage :@"View" :@"Okay"];
    popupView.view.frame = CGRectMake(0, -568, 320, 568);
    popupView.view.center = self.view.center;

    [self addChildViewController:popupView];    
    [self.view addSubview:popupView.view];
    [popupView didMoveToParentViewController:self];
}

这将保存对视图控制器的正确引用,以及能正确地传递各种视图控制器事件。在文档中读到这 UIViewController 和"视图控制器编程指南的 iOS"。

顺便说一句-你应该命名您的方法更好。示例︰

popupButtonPressed::

应命名︰

popupButtonPressed:buttonNumber:
赞助商