在 Objective-C 中,为什么在分配给指定类型的变量时需要强制转换? [英] In Objective-C, why is casting needed when assigning to a variable whose type is specified?

查看:56
本文介绍了在 Objective-C 中,为什么在分配给指定类型的变量时需要强制转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这种类型转换的用法经常出现,例如在按钮点击动作中:

This use of type casting comes up a lot, e.g. in a button tap action:

UIButton *button = (UIButton *)sender;

我的问题是为什么需要显式转换(UIButton *)".将sender"的值分配给变量button"是否已经有效地将其转换为指向 UIButton 的指针?

My question is why the explicit cast "(UIButton *)" is necessary. Doesn't assigning the value of "sender" to variable "button" already effectively cast it as a pointer to UIButton?

推荐答案

正如 Stephen 所说,这并不是真正必需的.

As Stephen said, it is not really required.

但这是一个风格和良好商业实践的问题.

But it is a quesiton of style and good business practice.

顺便说一句,当您省略它时,您会收到警告,而不是错误.只是为了摆脱警告,你可以简单地做:

BTW, when you omit it, you get a warning, not an error. Just for getting rid of the warning you could simply do:

someObject = (id) anotherObject;

这将适用于对任何类的任何对象的引用.你会看到几乎没有任何铸造完成.您始终可以分配给超类而无需强制转换:

That will work with references to any Object of any class. You see that there is hardly any casting acutally done. You can allways assign to superclasses without cast:

objectOfAClass = objectOfSubclassOfA;

最重要的是,它通过强迫您对自己实际在做什么进行短暂的思考来帮助您避免错误.

Bottom line is, it helps you avoiding mistakes by forcing you to think a very brief moment about what you are actually doing there.

这篇关于在 Objective-C 中,为什么在分配给指定类型的变量时需要强制转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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