简体   繁体   English

如何陷入Objective-C方法的完成阶段?

[英]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. 很简单,就可以轻松地实现animatedWithDuration:animations:completion:方法本身的不同或修改的实现。 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.) (这是一种非常脆弱且有些危险的技术,除非您非常了解自己在做什么,否则通常应在生产代码中避免使用这种技术;如果确实如此,则无论如何都会避免使用它。当它崩溃时,它会令人眼花blow乱,并使代码难以理解,但对调试和探索很有用。

A block is a value. 块是一个值。 It is a function literal, just a like "1" is an integer literal or @"string" is a string literal. 它是一个函数文字,就像“ 1”是整数文字或@"string"是字符串文字一样。 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; 我猜您想做的是:将不同于调用方提供的块传递给animatedWithDuration:animations:completion: 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 高温超导

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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