Objective-C将一个块类型转换为另一个得到了意外的结果

iwi*_*ill 5 floating-point objective-c forecasting ios objective-c-blocks

typedef (void (^blockType)());

我需要将具有不同参数类型的块转换为相同类型blockType,并在以后将其作为原始类型进行调用。但是在转换块类型时存在问题。

以下代码适用于任何参数类型,...

((blockType)^(BOOL b) {
    NSLog(@"BOOL: %d", b);
})(YES); // >> BOOL: 1
((blockType)^(int i) {
    NSLog(@"int: %d", i);
})(1); // >> int: 1
((blockType)^(double f) {
    NSLog(@"double: %f", f);
})(1.0 / 3); // >> double: 0.333333
((blockType)^(NSString *s) {
    NSLog(@"NSString *: %@", @"string");
})(1.0 / 3); // >> NSString *: string
Run Code Online (Sandbox Code Playgroud)

除了float

((blockType)^(float f) {
    NSLog(@"float: %f", f);
})(1.0f); // >> float: 0.000000
((blockType)^(float f) {
    NSLog(@"float: %f", f);
})(1.0f / 3); // >> float: 36893488147419103232.000000
Run Code Online (Sandbox Code Playgroud)

但是不用铸造也可以:

(^(float f) {
    NSLog(@"float without casting: %f", f);
})(1.0 / 3); // >> float without casting: 0.333333
Run Code Online (Sandbox Code Playgroud)

如何解释和解决呢?

iwi*_*ill 1

说明:将块称为blockType- (void (^)()),则块被视为(void (^)(double))

(void (^)(float))解决:调用时必须将块投射回原处。

  • 通过不同类型的函数指针(或块指针)调用函数总是很危险的。 (2认同)