Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ViewController.h
//
// ViewController.h
// runtime_special_case
//
// Created by tonyli on 4/10/18.
// Copyright © 2018 tonyli. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <objc/runtime.h>
@interface ViewController : UIViewController
@end
@interface UIImage (UIImageExtension)
- (void)swizzle_imageNamed:(NSString *)name;
@end
@interface SubUIImage : UIImage
- (void)hello_imageNamed:(NSString *)name;
- (void)swizzle_imageNamed:(NSString *)name;
@end
//
// ViewController.m
// runtime_special_case
//
// Created by tonyli on 4/10/18.
// Copyright © 2018 tonyli. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// UIImage*image= [SubUIImage imageNamed:@"trump180402.jpg"];
// UIImageView*imageview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
// imageview.image = image;
//
// [self.view addSubview:imageview];
// should print `swizzled method hello!`
[[SubUIImage new] swizzle_imageNamed:@"trump180402.jpg"];
// should print `Value of original method = trump180402.jpg`
[[UIImage new] swizzle_imageNamed:@"trump180402.jpg"];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
@implementation SubUIImage: UIImage
+ (void)load
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = [self class];
SEL originalSelector = @selector(hello_imageNamed:);
SEL swizzledSelector = @selector(swizzle_imageNamed:);
// Use class_getInstanceMethod for "normal" methods
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
// Swap the two methods.
BOOL success = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
if (success) {
class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
}else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
});
}
- (void)hello_imageNamed:(NSString *)name
{
NSLog(@"swizzled method hello!");
}
- (void)swizzle_imageNamed:(NSString *)name
{
NSLog(@"Value of override method = %@", name);
}
@end
@implementation UIImage (UIImageExtension)
- (void)swizzle_imageNamed:(NSString *)name
{
NSLog(@"Value of original method = %@", name);
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment