0

我有一个 UIViewController 的子类 -> MyPopUpViewController

@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 作为实例变量,因为它来自外部,并且可能有很多和多个这样的弹出窗口可以出现。到目前为止,我尝试了这个,由于没有被保留,它在委托调用中崩溃:

我的主视图控制器:

-(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 alloc] init];

..所以它会保留而不使其成为实例变量?

提前致谢。

4

2 回答 2

3

您应该通过调用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:
于 2013-12-06T04:01:45.920 回答
1

通常委托是弱引用而不是强引用。我,我自己,会把它命名为别的,以免混淆其他人。

此外,以下代码将不起作用:

-(void)popupButtonPressed:(MyPopUpViewController *)controller :(int)sentButtonNumber
{
    ...
    controller = nil;
}

控制器将nil在作用域结束时自动释放(设置为 )。

于 2013-12-16T19:30:11.967 回答