gpt4 book ai didi

objective-c - 在 objective-c : id or explicit type? 中更可取的是什么

转载 作者:行者123 更新时间:2023-12-04 03:27:08 24 4
gpt4 key购买 nike

什么更好,为什么?

类初始化方法和代码中的常用变量这种情况用什么比较好?

最佳答案

What is better and why ?

明确的键入信息总是更好,除非您出于某种原因不能使用它(见下文)。

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

很久很久以前,API 中的所有内容都使用 id。事实证明这是一个彻底的痛苦。脆弱并导致许多崩溃,这些崩溃会被特定类型捕获。

所以,它被改变了。 (这是 ~1994 年)。

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

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

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

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

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

如果你写了:

- (MyClass *) init;

在子类中:

- (MySubclass *) init;

你很可能会从 wazoo 中得到编译器警告,或者你必须对 wazoo 进行类型转换。

关于objective-c - 在 objective-c : id or explicit type? 中更可取的是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4702904/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com