ios – 如何使用NS_RETURNS_INNER_POINTER标志

我的任务是采用Modern Objective-C,我在
Xcode中使用重构工具:编辑>重构>转换为现代Objective-C语法.

在项目中我有一个方法return const void * type.并且在重构工具之后自动添加此方法后的NS_RETURNS_INNER_POINTER标志.我在FoundationOlderNotes检查了这个标志,但对我来说还不清楚.

>是否有必要为返回非对象指针类型的任何方法或属性添加NS_RETURNS_INNER_POINTER?
>究竟编译器在ARC中使用指针返回方法做了什么?

最佳答案 NS_RETURNS_INNER_POINTER是objc_returns_inner_pointer方法属性的特定于Cocoa的等效项.文档是
here

An Objective-C method returning a non-retainable pointer may be
annotated with the objc_returns_inner_pointer attribute to indicate
that it returns a handle to the internal data of an object, and that
this reference will be invalidated if the object is destroyed. When
such a message is sent to an object, the object’s lifetime will be
extended until at least the earliest of:

  • the last use of the returned pointer, or any pointer derived from it, in the calling function or
  • the autorelease pool is restored to a previous state.

Rationale

Rationale: not all memory and resources are managed with reference counts; it is common for objects to manage private resources in their own, private way. Typically these resources are completely encapsulated within the object, but some classes offer their users direct access for efficiency. If ARC is not aware of methods that return such “interior” pointers, its optimizations can cause the owning object to be reclaimed too soon. This attribute informs ARC that it must tread lightly.

The extension rules are somewhat intentionally vague. The autorelease pool limit is there to permit a simple implementation to simply retain and autorelease the receiver. The other limit permits some amount of optimization. The phrase “derived from” is intended to encompass the results both of pointer transformations, such as casts and arithmetic, and of loading from such derived pointers; furthermore, it applies whether or not such derivations are applied directly in the calling code or by other utility code (for example, the C library routine strchr). However, the implementation never need account for uses after a return from the code which calls the method returning an interior pointer.

  
  作为例外,如果接收器直接从带有precise lifetime semantics的__strong对象加载,则不需要扩展.
  
  

Rationale

Implicit autoreleases carry the risk of significantly inflating memory use, so it’s important to provide users a way of avoiding these autoreleases. Tying this to precise lifetime semantics is ideal, as for local variables this requires a very explicit annotation, which allows ARC to trust the user with good cheer.

回答您的具体问题:

>否,返回非对象指针的每个方法或属性都不必使用NS_RETURNS_INNER_POINTER进行批注.只有当它返回一个“内部”或“内部”指针时才应该这样做.也就是说,如果对象本身被释放,则该指针将变为无效.
>未指定编译器的确切功能.在一些实现中,它可以简单地保留并自动释放返回内部指针的对象.

点赞