objective-cclangfoundationnscopyinginstancetype

Using instancetype as the return type of a copy in Objective-C?


Using instancetype as a return value of init and related methods is the recommended way to proceed, see the latest clang features. However, what is the best practice w.r.t. the return value of copyWithZone: in the NSCopying protocol (see this thread for previous best practices)? It is not mentioned in the rules for inferring the class from the naming scheme of the methods in the clang article, but I don't see why it should be different than the return value of the alloc method.

Does the type inference not work for copy-methods? Should we still return instancetype or rather the specific class type we actually return?


Solution

  • You should NOT use instancetype. The obvious case here is that there is the immutable/mutable distinction -- A copy of an NSMutableString returns an NSString which you should treat as immutable. In that case, the API does not return an instance of the same type as the receiver.

    The other reason is that you should match the declaration's signature, as Josh Caswell noted (+1).

    Of course, nothing is preventing you from declaring your own protocol with the semantics and signature you desire.