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

Runtime in Objective-C

2017-05-26

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:

[gist https://gist.github.com/arkilis/038ec61241d83d7381e62dd5e9372e0a/]

To call above class or instance methods:

[gist https://gist.github.com/arkilis/a0ad311d8090c6b040beddfb136aa0ef/]

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:

[gist https://gist.github.com/arkilis/42aee407794d7e2ce9bcc7df1ead0381/]

Notice:

  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"

Reference

http://www.arkilis.me
https://developer.apple.com/reference/objectivec/1456712-objc_msgsend
http://chars.tech/2017/05/09/objc-runtime/

arkilis

Comments: