Objective-C naming conventions with ARC and possible caveats

為{幸葍}努か 提交于 2019-11-28 11:14:42

A method named newCustomer would fall within the new method family and is thus implicitly marked as returning an retained object. When both calling and called code is compiled with ARC, then ARC balances the extra retain with a release in the caller:

When returning from such a function or method, ARC retains the value at the point of evaluation of the return statement, before leaving all local scopes.

When receiving a return result from such a function or method, ARC releases the value at the end of the full-expression it is contained within, subject to the usual optimizations for local values.

Source

If newCustomer is implemented with manual reference counting and violates the naming convention (i.e., does not return a retained object), then the caller can either over release or under release, depending on the circumstances.

If the caller uses ARC, then the object returned from newCustomer will be overreleased - likely causing the program to crash. This is because the calling code will participate in the second half of the above process, without having had a corresponding retain performed prior to that.

If the calling code is not compiled with ARC, but the called code is (thus correctly implementing returning a retained object), then the behavior depends on the programmer following the naming conventions. If they release the returned value, then the object's reference count will be correctly managed. However, if the programmer believes that their new... method does violate the naming convention, and fails to manually insert a release in the calling code, then the object that was returned will leak.

All in all, as Martin R. points out in the comments, the critical determination is whether the naming conventions are followed in any environment including manual reference counting.

Just like any other language, when you violate some of the basic assumptions of the language you wander into the area of undefined behavior. At some point in the future, Apple may modify the internals of how -new... does reference counting. It is up to Apple to make sure that code which conforms to the expected use works, but they won't do that for non-conforming uses.

If you need to know what the actual behavior is for a particular version of a compiler running on a particular system, then you must test for it. Don't assume that behavior will be the same for other compilers or versions of the runtime.

In the end, undefined behavior is undefined behavior. When you build code relying on it, you will eventually be affected by a subtle and difficult to diagnose defect.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!