声明变量"id"与输入变量"id"有什么区别?和"NSObject *"? [英] What's the difference between declaring a variable "id" and "NSObject *"?

查看:114
本文介绍了声明变量"id"与输入变量"id"有什么区别?和"NSObject *"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Objective-C中,声明变量id与声明NSObject *有什么区别?

In Objective-C, what's the difference between declaring a variable id versus declaring it NSObject *?

推荐答案

使用类型为id的变量,您可以将其发送给任何已知消息,并且编译器不会抱怨.使用类型为NSObject *的变量,您只能向其发送由NSObject声明的消息(而不是任何子类的方法),否则它将生成警告.通常,id是您想要的.

With a variable typed id, you can send it any known message and the compiler will not complain. With a variable typed NSObject *, you can only send it messages declared by NSObject (not methods of any subclass) or else it will generate a warning. In general, id is what you want.

进一步的解释:所有对象本质上都是id类型.声明静态类型的目的是告诉编译器假设该对象是该类的成员".因此,如果向它发送未声明该类的消息,则编译器会告诉您:等等,该对象不应该获得该消息!"同样,如果两个类具有名称相同但签名(即参数或返回类型)不同的方法,则它可以猜测已为变量声明的类所表示的方法.如果将其声明为id,编译器将举起手来告诉您:好,我在这里没有足够的信息.我随机选择一个方法签名." (不过,通常不会通过声明NSObject*来帮助.通常冲突是在两个更具体的类之间.)

Further explanation: All objects are essentially of type id. The point of declaring a static type is to tell the compiler, "Assume that this object is a member of this class." So if you send it a message that the class doesn't declare, the compiler can tell you, "Wait, that object isn't supposed to get that message!" Also, if two classes have methods with the same name but different signatures (that is, argument or return types), it can guess which method you mean by the class you've declared for the variable. If it's declared as id, the compiler will just throw its hands up and tell you, "OK, I don't have enough information here. I'm picking a method signature at random." (This generally won't be helped by declaring NSObject*, though. Usually the conflict is between two more specific classes.)

这篇关于声明变量"id"与输入变量"id"有什么区别?和"NSObject *"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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