Quantcast
Channel: Notes of a Developer » Category
Viewing all articles
Browse latest Browse all 2

How to extend existing method

$
0
0

With blocks it’s more easy if you need extend your method. But if you will need extend some method of another class, not yours, and you will not be able to get the sources then this solution for you. (And if you will not be able or does not have any reason for creating a subclass)

1. You need create a category of class

2. import runtime in implementation file (.m)

1
#import <objc/runtime.h>

3. implement your method inside category, for example :

1
2
3
4
5
6
7
8
9
- (void) extend_method {

// your code

//  here will be performed the original method
    [self extend_method];
   
// your code
}

It looks like this method has recursive calls itself, but it’s not true. Look next step

4. add method for replace (you can use +initialize or +load)

1
2
3
4
5
+ (void) initialize {
    Method original = class_getInstanceMethod(self, @selector(method));
    Method replacement = class_getInstanceMethod(self, @selector(extend_method));
    method_exchangeImplementations(original, replacement);
}

Done!

The post How to extend existing method appeared first on Notes of a Developer.


Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images