加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何在Objective-C中正确使用UIAlertAction处理程序

发布时间:2020-12-16 10:00:11 所属栏目:百科 来源:网络整理
导读:简单地说,我想在UIAlertAction处理程序中调用一个方法或引用我的类中的变量. 我是否需要将块传递给此处理程序,还是有其他方法可以实现此目的? @interface OSAlertAllView ()@property (nonatomic,strong) NSString *aString;@end@implementation OSAlertAll
简单地说,我想在UIAlertAction处理程序中调用一个方法或引用我的类中的变量.

我是否需要将块传递给此处理程序,还是有其他方法可以实现此目的?

@interface OSAlertAllView ()
@property (nonatomic,strong) NSString *aString;
@end

@implementation OSAlertAllView

+ (void)alertWithTitle:(NSString *)title message:(NSString *)msg cancelTitle:(NSString *)cancel inView:(UIViewController *)view
{
    __weak __typeof(self) weakSelf = self;

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:msg
                                                                preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:cancel style:UIAlertActionStyleDefault
        handler:^(UIAlertAction * action) {
            // I'd like to reference a variable or method here
            weakSelf.aString = @"Apples"; // Not sure if this would be necessary
            self.aString = @"Apples"; // Member reference type 'struct objc_class *' is a pointer Error
            [self someMethod]; // No known class method Error
        }];

    [alert addAction:defaultAction];
    [view presentViewController:alert animated:YES completion:nil];
}

- (void)someMethod {

}

解决方法

alertWithTitle …方法的开头意味着它是一个类方法.当你调用它时,self将是OSAlertAllView类,而不是OSAlertAllView类型的实例.

有两种方法可以改变它以使其工作.

将方法开头的更改为 – 使其成为实例方法.然后你可以在实例而不是类上调用它.

// Old Class Method Way
[OSAlertAllView alertWithTitle:@"Title" message:@"Message" cancelTitle:@"Cancel" inView:viewController];

// New Instance Methods Way
OSAlertAllView *alert = [OSAlertAllView new];
[alert alertWithTitle:@"Title" message:@"Message" cancelTitle:@"Cancel" inView:viewController];

另一种方法是在alertWithTitle中创建一个OSAlertAllView实例…并将self替换为该对象.

+ (void)alertWithTitle:(NSString *)title message:(NSString *)msg cancelTitle:(NSString *)cancel inView:(UIViewController *)view
{
    OSAlertAllView *alertAllView = [OSAlertAllView new];

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:msg
                                                                preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:cancel style:UIAlertActionStyleDefault
        handler:^(UIAlertAction * action) {
            alertAllView.aString = @"Apples";
            [alertAllView someMethod];
        }];

    [alert addAction:defaultAction];
    [view presentViewController:alert animated:YES completion:nil];
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读