看到这个场景:
@property (nonatomic,copy) UIImage * (^bgImageBlock)(void);
bgImageBlock
block 变量的定义:
objDrawing.bgImageBlock = ^(){
return (UIImage *)NULL;
};
bgImageBlock 具有返回类型 UIImage,如果我像这样传递 NULL:
objDrawing.bgImageBlock = ^(){
return NULL;
};
会给出编译时错误:Incompitable block pointer type assigning to UIImage.
而如果我采用简单的 UIImage 变量并将其分配为 NULL,那绝对没问题。那么为什么在 Blocks 的情况下它不能在没有类型转换的情况下接受 NULL。 ?
最佳答案
如果您没有明确告诉编译器,编译器会根据您返回的对象类型推断 block 返回类型。所以,在这种情况下:
objDrawing.bgImageBlock = ^(){
return NULL;
};
...我假设它看到了 NULL
并推断您的 block 的返回类型是 void *
,NULL
的类型.这与您的属性类型不匹配,因此编译器会提示。 (请注意,错误与“ block 指针类型”有关;这是 block 属性的声明与您试图存储在其中的 block 之间的不匹配。)
如果你明确地告诉它你的类型,你应该能够使用你简单的 NULL 返回:
objDrawing.bgImageBlock = ^UIImage*(){
return NULL;
};
block 类型是从返回类型中推断出来的,记录在案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 的进展”。 (参见标题为“返回类型推断”的部分)。
关于ios - 为什么 NULL 需要用 block 进行类型转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25599531/