chevron-up bell reply instagram twitter2 feed3 finder search-25px-p0

Runtime in Objective-C


Objective-C is a dynamic language. With Runtime, objects can be represented through struct in C, and methods can be done via c language function. Runtime is written in assembly and c. With the benefits of Runtime, we have another way to call class and instance methods.

The following example shows how to use Runtime to call class and instance methods:


To call above class or instance methods:


However, the above code will throw errors, as Apple suggests not to use low-level methods since iOS 5. To use objc_msgSend, you need to #import <objc/message.h> and:

##Now what can we do with Runtime

The above piece of code shows get a request from a given url. However, in practice, we need to check the variable url not equals to nil. Of course we can do like:

But it will become tedious and generate large amount of redundant code every time when you want to use it. Think about this, in Python, we can do this through decorator. So is there any easy way to accomplish the same in Objective-C? The answer is using :

  • category: extend current (original) class
  • Runtime: "override" current (original) class methods

So we can create a category:



  1. static method load is automatically called by NSURL
  2. Runtime method method_exchangeImplementations swap method name URLWithString: and new_URLWithString:. So from now on, when you do NSURL *url = [NSURL URLWithString:@"xxxxx"], Runtime will not call the original URLWithString: method, instead it actually will call new_URLWithString at behind.
  3. Don't forget to #import "NSURL+CheckURL.h"