I need to check the return type of an NSInvocation to see if it is an object (from there I can use isKindOfClass: to check the exact kind of object). I see that NSInvocation has an NSMethodSignature, which in turn has methodReturnType. However, the documentation gives the following warning:
This encoding is implementation-specific, so applications should use it with caution.
So, how do I safely check if the return type is an object? Is there a decode variant of @encode(type-name)?
In short, you can’t. At least, not with 100% fidelity.
For simple types like doubles, floats, ints, ids, etc… you can check the return type and then deal with it in a platform specific fashion. For more complex types — structs, C++ objects, etc… — you could go down the path of trying to figure out just how, exactly, the C ABI would have laid out the data on a per-ABI basis, but you’ll end up re-inventing the compiler in the process.
Fortunately, there are some really comprehensive examples of how all this works. Both the PyObjC and RubyCocoa (MacRuby) projects are open source and provide relatively complete support for arbitrary return values. Relatively; you’ll still be hosed on complex types.
All in all, Objective-C is purely dynamic at dispatch but very much a C derived static language in terms of argument passing and return values.
Missed your final sentence. The derp is strong prior to coffee.
This is the set of characters that might be returned by
methodReturnType.You’ll be looking for
@. Given thatmethodReturnTypereturns aconst char *, you may encounter cases where an object return type returns more than just an@; there may be modifiers attached to it. You’ll have to test a boatload of method’s return types to see if that is actually the case (the generation of said metadata has changed over the years and is also influenced by the use of various keywords in method declarations).However, most of the time
@is good enough to conclude that it is an object return type.Mostwill increase in truthiness for methods of your own declaration (where you, hopefully, don’t do anything exceedingly odd, from the compiler’s perspective).