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

8
简单来说,我想从我的类中在一个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 {

}

1
你的 alertWithTitle... 方法是一个类方法,而不是一个实例方法。将其改为实例方法,你就可以做你试图做的事情了。 - rmaddy
1个回答

12

在你的 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];
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接