如何执行UIAlertAction的处理程序?

Ben*_*ero 4 objective-c ios objective-c-blocks uialertviewdelegate uialertaction

我正在尝试编写一个帮助程序类,以允许我们的应用程序支持UIAlertActionUIAlertView.但是,在编写alertView:clickedButtonAtIndex:方法时UIAlertViewDelegate,我遇到了这个问题:我看不到在a的处理程序块中执行代码的方法UIAlertAction.

我试图通过UIAlertAction在一个名为的属性中保留一个s 数组来做到这一点handlers

@property (nonatomic, strong) NSArray *handlers;
Run Code Online (Sandbox Code Playgroud)

然后实现这样的委托:

- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    UIAlertAction *action = self.handlers[buttonIndex];
    if (action.enabled)
        action.handler(action);
}
Run Code Online (Sandbox Code Playgroud)

但是,没有action.handler属性,或者确实有任何我可以看到的方法来获取它,因为UIAlertAction标题只有:

NS_CLASS_AVAILABLE_IOS(8_0) @interface UIAlertAction : NSObject <NSCopying>

+ (instancetype)actionWithTitle:(NSString *)title style:(UIAlertActionStyle)style handler:(void (^)(UIAlertAction *action))handler;

@property (nonatomic, readonly) NSString *title;
@property (nonatomic, readonly) UIAlertActionStyle style;
@property (nonatomic, getter=isEnabled) BOOL enabled;

@end
Run Code Online (Sandbox Code Playgroud)

有没有其他方法来执行handler块中的代码UIAlertAction

Dre*_*w H 5

经过一些实验,我才想到这一点.事实证明,处理程序块可以作为函数指针进行转换,并且可以执行函数指针.

像这样

//Get the UIAlertAction
UIAlertAction *action = self.handlers[buttonIndex];

//Cast the handler block into a form that we can execute
void (^someBlock)(id obj) = [action valueForKey:@"handler"];

//Execute the block
someBlock(action);
Run Code Online (Sandbox Code Playgroud)