ios – 为什么NULL需要使用块进行类型转换?

看这个场景:

@property (nonatomic,copy) UIImage * (^bgImageBlock)(void);

bgImageBlock块变量的定义:

objDrawing.bgImageBlock = ^(){
         return (UIImage *)NULL;
    };

bgImageBlock有返回类型UIImage,如果我像这样传递NULL:

objDrawing.bgImageBlock = ^(){
         return NULL;
    };

会给编译时错误:分配给UIImage的不兼容的块指针类型.

如果我采用简单的UIImage变量并将其赋值为NULL,那绝对没问题.那么为什么在Block的情况下它不能在没有类型转换的情况下接受NULL. ?

最佳答案 如果您没有明确告诉它,编译器会从您返回的对象类型中推断出块返回类型.所以,在这种情况下:

objDrawing.bgImageBlock = ^(){
     return NULL;
};

…我假设它看到NULL并推断块的返回类型是void *,类型为NULL.这与您的属性类型不匹配,因此编译器会抱怨. (请注意,错误与“块指针类型”有关;它是块属性声明与您尝试存储在其中的块之间的不匹配.)

如果你明确告诉它你的类型,你应该能够使用简单的NULL返回:

objDrawing.bgImageBlock = ^UIImage*(){
     return NULL;
};

从返回类型推断出的块类型记录为in the Clang documentation

The return type is optional and is inferred from the return statements. If the return statements return a value, they all must return a value of the same type. If there is no value returned the inferred type of the Block is void; otherwise it is the type of the return statement value.

返回类型的推断,以及编译器为您检查指针类型的事实,以及在出现不匹配时产生的错误,在2013 WWDC session“Objective-C的进展”中提到. (参见标题为“返回类型推断”的部分).

点赞