Skip to content

Instantly share code, notes, and snippets.

@usagimaru
Last active April 26, 2024 18:26
Show Gist options
  • Save usagimaru/69887a118a6a277113dcaca034b393c3 to your computer and use it in GitHub Desktop.
Save usagimaru/69887a118a6a277113dcaca034b393c3 to your computer and use it in GitHub Desktop.
About Return Types of `method_copyReturnType()` of the Objective-C Runtime API

I found some documentation of the types returned by method_copyReturnType() in the Objective-C runtime API. These mysterious characters are called Type Encodings in Objective-C and are unique codes represented by one or fewer characters.

I note it here for my own benefit.

  • c = char
  • B = BOOL / bool / _bool
  • s = short
  • i = int
  • I = unsigned int?
  • l = long
  • q = long long
  • L = unsigned long
  • C = unsigned char
  • S = unsigned short
  • Q = unsigned long long (bitmask?)
  • f = float
  • d = double
  • v = void
  • Vv = void
  • * = char*
  • @ = id object
  • : = SEL
  • # = Class
  • ^TYPE = pointer
  • rTYPE = const
  • N = inout
  • bNUMBER = NUMBER bits
  • ? = unknown type
  • [TYPE] = array
  • {NAME=type...} = structure
  • (NAME=type...) = union
  • {CGRect={CGPoint=dd}{CGSize=dd}} = CGRect
  • {CGPoint=dd} = CGPoint
  • {CGSize=dd} = CGSize

https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html#//apple_ref/doc/uid/TP40008048-CH100

@usagimaru
Copy link
Author

usagimaru commented Apr 26, 2024

To dynamically retrieve information from a method name using the Objective-C Runtime API in Swift

let targetClass = NSClassFromString("CLASS_NAME")
let targetSelector = NSSelectorFromString("SELECTOR_NAME")
let method = class_getInstanceMethod(targetClass, targetSelector)

let returnType = method_copyReturnType(method)
let returnTypeName = String(cString: returnType)

let methodName = methodName(method: method)

// Needs some unwrapping

print("\(returnTypeName) \(methodName)")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment