【问题标题】:How to properly use a UIAlertAction handler in Objective-C如何在 Objective-C 中正确使用 UIAlertAction 处理程序
【发布时间】:2015-11-20 17:14:05
【问题描述】:

简单地说,我想在 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... 方法是类方法,而不是实例方法。让它成为一个实例方法,你就可以做你想做的事了。

标签: objective-c uialertcontroller


【解决方案1】:

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];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-03
    相关资源
    最近更新 更多