1

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?

Michael Teper
  • 4,591
  • 2
  • 32
  • 49
  • 1
    Swizzling, as I understand it, isn't going to work because you don't have a selector to work with. Can you give an example of what you want to accomplish? – Phillip Mills May 12 '15 at 22:19

2 Answers2

3

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.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610
2

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

CRD
  • 52,522
  • 5
  • 70
  • 86
  • That sounds about right. Could you point me at an example of wrapping a block? Let's say the initial block did X, Y, and Z, and for the sake of this example I wanted to follow that up with a call to `NSLog(@"Done!")` – Michael Teper May 13 '15 at 07:23
  • @MichaelTeper - maybe the use of "wrap" suggested something special, it isn't. You know about swizzling. In your method that replaces the method and calls the original pass as the continuation block to the original a block which first calls the caller supplied block and then calls `NSLog` - i.e. a block that "wraps" the caller supplied one. – CRD May 13 '15 at 07:51