ios - 如何执行 UIAlertAction 的处理程序?

标签 ios objective-c objective-c-blocks uialertviewdelegate uialertaction

我正在尝试编写一个帮助程序类,让我们的应用程序支持 UIAlertActionUIAlertView。但是,在为 UIAlertViewDelegate 编写 alertView:clickedButtonAtIndex: 方法时,我遇到了这个问题:I see no way to execute the code in the handler block of一个 UIAlertAction

我试图通过在名为 handlers 的属性中保留一组 UIAlertAction 来实现这一点

@property (nonatomic, strong) NSArray *handlers;

然后像这样实现一个委托(delegate):

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

但是,没有 action.handler 属性,或者实际上我可以看到获取它的任何方式,因为 UIAlertAction header 只有:

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

是否有其他方法可以执行 UIAlertActionhandler block 中的代码?

最佳答案

经过一些实验,我才明白这一点。事实证明,处理程序 block 可以转换为函数指针,并且可以执行函数指针。

像这样

//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);

关于ios - 如何执行 UIAlertAction 的处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29773960/

相关文章:

ios - LocationManager 调度队列问题

javascript - iOS YouTube嵌入式播放器在单击红色按钮时无法播放视频

ios - CoreBluetooth 和 BluetoothManager,设备不是 BLE

objective-c - block 内存管理

ios - 如何从另一个图像的一部分创建图像?

ios - 执行时事件指示器不显示

ios - 低功耗蓝牙 iOS 应用程序

objective-c - 在测试 iOS Swift 中访问只读属性

objective-c - 可以为 block 中的自动合成属性使用下划线(强引用循环)

objective-c - 在为 Objective-C 进行单元测试时,您如何测试 block ?