Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call the original method from swizzled one?

Tags:

objective-c

How to call the original method from swizzled one?

The original method is replaced by the code:

[[UIWindow class] jr_swizzleMethod:@selector(originalMethod) withMethod:@selector(swizzledMethod) error:nil];

The following code on swizzledMethod makes recursion!

[self originalMethod];

How to solve this problem?

I use the following library for swizzling:

// JRSwizzle.h semver:1.0
//   Copyright (c) 2007-2011 Jonathan 'Wolf' Rentzsch: http://rentzsch.com
//   Some rights reserved: http://opensource.org/licenses/MIT
//   https://github.com/rentzsch/jrswizzle

#import <Foundation/Foundation.h>

@interface NSObject (JRSwizzle)

+ (BOOL)jr_swizzleMethod:(SEL)origSel_ withMethod:(SEL)altSel_ error:(NSError**)error_;
+ (BOOL)jr_swizzleClassMethod:(SEL)origSel_ withClassMethod:(SEL)altSel_ error:(NSError**)error_;

@end
like image 316
Dmitry Avatar asked Nov 08 '12 17:11

Dmitry


People also ask

What is a swizzle method?

Swizzling is the act of changing the functionality of a method by replacing the implementation of that method with another, usually at runtime. There are many different reasons one might want to use swizzling: introspection, overriding default behavior, or maybe even dynamic method loading.

What is method sizzling?

Method Swizzling is a dynamic feature that can exchange the implementations of two methods in runtime and it's often used to modify the behavior of framework classes as well. This means it can implement some complex functions conveniently.

Why method swizzling is used?

Method swizzling is the process of replacing the implementation of a function at runtime. Swift, as a static, strongly typed language, did not previously have any built-in mechanism that would allow to dynamically change the implementation of a function.

What is message swizzling?

Swizzling (other languages call this “monkey patching”) is the process of replacing a certain functionality or adding custom code before the original code is called.


2 Answers

The answer is very interesting:

[self swizzledMethod]; // will call originalMethod
like image 107
Dmitry Avatar answered Oct 20 '22 22:10

Dmitry


I had gone through creating method swizzling for iOS 5

and I put up an explanation of it here.

Method Swizzling in iOS 5?

essentially every call to the original method is going to yours. And therefore every call to your method should be directed back to the original. (if the swizzle was set up correctly)

Hope that helps

like image 33
The Lazy Coder Avatar answered Oct 20 '22 21:10

The Lazy Coder