简体   繁体   中英

How to swizzle into completion block of an Objective-C method?

Let's take this method as an example:

+ (void)animateWithDuration:(NSTimeInterval)duration
                 animations:(void (^)(void))animations
                 completion:(void (^)(BOOL finished))completion

It's simple enough to swizzle in a different or modified implementation of animatedWithDuration:animations:completion: method itself. What if I am instead interested in doing this for the completion block?

Swizzling refers to modifying the class or object meta data in order to call different implementation for a given selector. (It is a very fragile, and somewhat dangerous technique that should generally be be avoided in production code unless you are very aware of what you're doing, and if you are, you'll probably avoid it anyway. When it blows up, it blows up gloriously and makes code incredibly difficult to understand. It is useful for debugging and exploration, however.)

A block is a value. It is a function literal, just a like "1" is an integer literal or @"string" is a string literal. There is no object or class to swizzle. If you want to modify the value, you have to modify the value, just like you would modify the duration in your example.

As others have pointed out, "swizzle" is used to refer to changing a method implementation, so you've the wrong term but that's not major.

I'm guessing what you want to do is either: pass a different block to animatedWithDuration:animations:completion: than the caller supplies; or wrap the block the caller supplies in your own block - which amounts to much the same thing.

If my guess is correct then you can swizzle the method replacing it by one which calls the original passing blocks of your choice, which could be wrappers around the blocks the caller supplied.

HTH

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM