为什么`nil`的类型不是`id`而是`void *` [英] why the type of `nil` is not `id` but `void *`

查看:120
本文介绍了为什么`nil`的类型不是`id`而是`void *`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此代码中

id (^block)(void) = ^(void) {
    return nil;
};

我有这个错误

使用类型为'void *(^)(void)'的表达式初始化'id(^ __ strong)(void)'的不兼容块指针类型

Incompatible block pointer types initializing 'id (^__strong)(void)' with an expression of type 'void *(^)(void)'

所以我必须将nil显式转换为id类型

So I have to explicitly cast nil to id type

id (^block)(void) = ^(void) {
    return (id)nil;
};

使编译器满意.购买为什么nil不是id类型?

to make compiler happy. Buy why nil is not id type?

对于此代码

__typeof__(nil) dummy;
dummy = [NSObject new];

Objective-C指针类型'NSObject *'隐式转换为C指针类型'typeof((((void *)0))'(aka'void *')需要桥接转换

Implicit conversion of Objective-C pointer type 'NSObject *' to C pointer type 'typeof (((void *)0))' (aka 'void *') requires a bridged cast

是说nil(void *)0,但不只是与NULL相同吗?我虽然nil应该是(id)0,而Nil应该是(Class)0?

which is saying nil is (void *)0, but isn't just same as NULL? I though nil should be (id)0 and Nil should be (Class)0?

我正在使用Xcode 4.6.2

I am using Xcode 4.6.2

编译器:Apple LLVM版本4.2(clang-425.0.28)(基于LLVM 3.2svn)

Compiler: Apple LLVM version 4.2 (clang-425.0.28) (based on LLVM 3.2svn)

推荐答案

您正在为块文字使用推断的返回类型,但不必这样做.

You're using an inferred return type for your block literal, but you don't have to.

消除该错误的正确方法是为块文字提供返回类型:

The correct way to remove that error is to provide a return type for the block literal:

id (^block)(void) = ^id{
    return nil;
};

这篇关于为什么`nil`的类型不是`id`而是`void *`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆