Objective-c: id 还是显式类型更可取? [英] What is preferable in objective-c: id or explicit type?

查看:62
本文介绍了Objective-c: id 还是显式类型更可取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么更好,为什么?

在类 init 方法和代码中的常用变量等情况下,什么更好?

What is better in such situations as the class init method and usual variables in a code ?

推荐答案

什么更好,为什么?

What is better and why ?

显式输入信息总是更好,除非您出于某种原因无法使用它(见下文).

Explicit typing information is always better unless you just can't use it for some reason (see below).

它允许编译器更严格地验证代码,并会在编译时捕获许多错误,否则会导致您的应用在运行时崩溃.

It allows the compiler to much more stringently validate the code and will catch many errors at compile time that would otherwise cause your app to crash at runtime.

很久很久以前,API 中的所有内容都使用 id.这被证明是一个完全的屁股痛.脆弱并导致许多崩溃,而这些崩溃本来可以用特定类型捕获.

A long, long, time ago, everything in the APIs used id. This proved to be a complete pain in the butt; fragile and led to many crashes that would have been caught with specific types.

所以,它被改变了.(这是 1994 年左右).

So, it was changed. (This was ~1994).

在这种情况下什么更好类 init 方法和通常的代码中的变量?

What is better in such situations as the class init method and usual variables in a code ?

对于 init,您别无选择,只能使用通用的 (id) 返回类型.Objective-C 既不支持协变声明,也不支持逆变声明,也没有一种机制可以泛化 init 的声明,同时还提供对特定类型检查的支持.

For init, you have no choice but to use the generic (id) return type. Objective-C does not support either co-variant or contra-variant declarations, nor is there a mechanism for generalizing the declaration of init while also providing support for specific type checking.

同样适用于 retainobjectAtIndex:addObject: 和许多其他采用或返回多种对象(或将它们作为参数).

Same goes for retain, objectAtIndex:, addObject: and many other methods that take or return one of many kinds of objects (or take 'em as arguments).

而且,不,idNSView* 之间绝对没有任何性能差异.

And, no, there is absolutely no performance difference whatsoever between id and, say, NSView*.

你能举个例子吗?打字会出现问题吗?

can you give an example when explicit typing will cause a problem please?

如果你写道:

- (MyClass *) init;

在子类中:

- (MySubclass *) init;

您很可能会收到 wazoo 的编译器警告,或者您必须对 wazoo 进行类型转换.

You'd get compiler warnings out the wazoo most likely or you'd have to typecast out the wazoo.

这篇关于Objective-c: id 还是显式类型更可取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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