在为 init 调用 func 之后,UIAlertController 仍然为 nil

after calling an func for init the UIAlertController remains nil

我有 2 个要在不同情况下显示的警报,我在开始时为 init 警报编写了一个通用函数,稍后更改消息,但是当我尝试显示警报时,我得到崩溃。当我在运行时检查 notesAlert 时,它仍然是 nil。

谁能解释一下我做错了什么?

    @interface viewController (){
        UIAlertController *tableAlert;
        UIAlertController *notesAlert;
    }
    @end

    @implementation viewController
    
    - (void)viewDidLoad {
       [super viewDidLoad];
       [self initAlert:tableAlert];
       [self initAlert:notesAlert];
    }
    
// func to init the alerts
    -(void)initAlert:(UIAlertController*)alert{
        alert = [UIAlertController alertControllerWithTitle: @"" message: @"" preferredStyle:UIAlertControllerStyleActionSheet];
        [alert setModalPresentationStyle:UIModalPresentationPopover];
        [alert.popoverPresentationController setSourceView:self.view];
        
        UIPopoverPresentationController *popover = [alert popoverPresentationController];
        CGRect popoverFrame = CGRectMake(0,0, self.view.frame.size.width/2, self.view.frame.size.width/2);
        popover.sourceRect = popoverFrame;
        UIAlertAction *dismiss = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:nil];
        [alert addAction:dismiss];
    }
    
    - (IBAction)showNotes:(id)sender {
        
// here the notesAlert is still nil
            [notesAlert setTitle:@"oops"];
            [notesAlert setMessage:@"you pressed the wrong one"];
    
        [self presentViewController:notesAlert animated:YES completion:nil];
    
    }
    @end

[self initAlert: notesAlert]; 不会创建 notesAlert。相反,您可以使用 notesAlert = [self initAlert];

也许是这样的:

@interface ViewController () {
    UIAlertController *tableAlert;
    UIAlertController *notesAlert;
}
@end

@implementation ViewController

- (void)viewDidLoad {
   [super viewDidLoad];
   self.tableAlert = [self initAlert];
   self.notesAlert = [self initAlert];
}

// func to init the alerts
- (UIAlertController *) initAlert {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle: @"" message: @"" preferredStyle: UIAlertControllerStyleActionSheet];
    [alert setModalPresentationStyle:UIModalPresentationPopover];
    [alert.popoverPresentationController setSourceView: self.view];
    
    UIPopoverPresentationController *popover = [alert popoverPresentationController];
    CGRect popoverFrame = CGRectMake(0,0, self.view.frame.size.width/2, self.view.frame.size.width/2);
    popover.sourceRect = popoverFrame;
    UIAlertAction *dismiss = [UIAlertAction actionWithTitle: @"Ok" style: UIAlertActionStyleDefault handler:nil];
    [alert addAction: dismiss];

    return alert;
}