Swizzling Copy method of UIResponder

475 Views Asked by At

I am swizzling Copy: and Paste: method of UIResponder. I have to write the copied content to a private pasteboard.

- (void)copyToPrivatePasteboard:(id)sender
{
    UIPasteboard *privatePasteboard = [self getPrivatePasteboard];
    [privatePasteboard setString:@""];//How to get the copied string to store in pasteboard.
}

How can i write copied string to pasteboard. The parameter i am getting is of type id. If i convert it to NSString, it won't be proper because it is the sender who is calling this method (UIMenuController).

1

There are 1 best solutions below

5
On

If I understand you correct, you want to replace UIResponder's -copy: with the code in you Q. (And doing the same thing with -paste:.)

This is the answer to your Q. But there are some comments at the end:

  • If you swizzle a method, self will point to the receiver of the message. In your case it is the instance of UIResponder. So you have to grab the data using self. How can you do this? Not in general, because:

  • -copy: can contain more than "Put my data to the pasteboard." It is a method. The code there can deal with other things you cannot not know. So you cannot substitute it that easy.

  • Because of this -copy: is typically overwritten in subclasses. (I think, that it does nothing in its UIResponder implementation.) Swizzling -copy: in UIResponder will not change any behaviour in an instance of a subclass. Are you familiar with the concept of the responder chain?

Probably there are better ways to accomplish your goal:

  • If you really want to do some swizzling, because it is cool, I would prefer +generalPasteboard (UIPasteboard).

  • Butmaybe you should describe your final goal with more details. Probably there is a completly different way to reach it.