NSNotification 上的对象是否需要强制转换?
当我收到 NSNotification
时,我是否需要强制转换 notification.object
?假设我知道 notification.object
将是 MyClass
的实例,并且我执行以下操作:
MyClass *myClass = notification.object;
这里需要进行任何转换吗? 上述分配如何不同于:
MyClass *myClass = (MyClass *)notification.object;
When I receive an NSNotification
do I ever need to cast notification.object
? Suppose I know notification.object
will be an instance of MyClass
and I do the following:
MyClass *myClass = notification.object;
Is any casting necessary here? How is the above assignment different from:
MyClass *myClass = (MyClass *)notification.object;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,这是完全没有必要的,并且不会改变程序的任何行为。强制转换仅在编译时发生,对于指针而言,仅用于向编译器保证您知道对象是什么类型。
例如,如果您将
Subclass
类型的变量设置为返回Superclass
类型的方法的结果,编译器可能会抱怨赋值,其中您知道您要返回的实际对象是Subclass
类型。在这种情况下,您将转换为子类。例如,notification.object
的类型是id
,一个通用对象指针,编译器非常乐意将这样的指针分配给任何其他类型的指针。No, it is entirely unneccessary and does not change anything about the behavior of your program. Casting only happens at compile time, and in the case of pointers, is just used to assure the compiler that you know what type the object is.
The compiler may complain about an assignment if you are, for example, setting a variable of type
Subclass
to the result of a method that returns typeSuperclass
, where you know that the actual object you are going to get back is of typeSubclass
. In that case, you would cast to the subclass. E.g.,The type of
notification.object
isid
, a generic object pointer, and the compiler is perfectly happy to assign such a pointer to any other type of pointer.不需要。Objective-C 不需要从
id
类型到另一个对象类型的转换。No. Objective-C doesn't require a cast from type
id
to another object type.