gpt4 book ai didi

objective-c - 为什么 ARC 禁止调用未声明的方法?

转载 作者:太空狗 更新时间:2023-10-30 03:50:28 25 4
gpt4 key购买 nike

当使用手动内存管理时,我们可以编写对类中未声明的方法的调用。在这种情况下,我们在编译期间得到的只是警告。这是维基百科关于最独特的 Objective-C 功能之一的陈述:

The Objective-C model of object-oriented programming is based on message passing to object instances. In Objective-C one does not simply call a method; one sends a message. This is unlike the Simula-style programming model used by C++. The difference between these two concepts is in how the code referenced by the method or message name is executed. In a Simula-style language, the method name is in most cases bound to a section of code in the target class by the compiler. In Smalltalk and Objective-C, the target of a message is resolved at runtime, with the receiving object itself interpreting the message

那么为什么在ARC中会出现编译错误呢?破坏该语言如此强大功能的原因是什么?有什么重要的事情我不知道?有人可以解释一下吗?谢谢

最佳答案

在这个讨论中有一些关于它的信息:

Under ARC, the compiler needs to now exactly the kind of ownership the method returns. The default in this case is that the object is not owned by the caller, but in the actual declaration the object may be owned by the caller ("ns_returns_retained" attribute), conversely, you may have a owning method like newBar that returns a non-retained object ("ns_returns_not_retained" attribute), in the former case you get an under-release in the latter you get an over-release, which is detrimental to ARC.

To make ARC deterministic, the compiler has to assume a lot of things so certain behaviours that were okay before are made illegal in ARC to ensure that the behaviour is consistent.

这个回复似乎来自一位 Apple 开发人员:

Our reasoning was split about 50/50 between (1) needing to be more careful about types and ownership and (2) wanting to eliminate an embarrassing wart in the language (not being allowed to complain about completely unknown methods with anything more strenuous than a warning). There is really no legitimate reason to call a method that's not even declared somewhere. The ability to do this makes some really trivial bugs (e.g. typos in selectors) runtime failures instead of compile failures. We have always warned about it. Fix your code.

所以主要论点是编译器需要知道的所有权返回值

关于objective-c - 为什么 ARC 禁止调用未声明的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20582642/

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