質問

I am interesting if it possible to substitute the method body of UIWebView in a runtime? I can't subclass UIWebView

For instance, I need to implement:

- (void) paste:(id)sender;
or
- (BOOL) canPerformAction:(SEL)action withSender:(id)sender;
役に立ちましたか?

解決

Have you tried out the runtime method method_setImplementation?

Like so:

static IMP originalPaste = NULL;

void myPaste(id rcv, SEL cmd, id sender)
{
    // Your implementation here
}

…
{
    …
    Method m = class_getInstanceMethod([UIWebView class], @selector(paste:));
    originalPaste = method_setImplementation(m, myPaste);
    …
}

Using the originalPaste you can perform a super call within your implementation.

他のヒント

Yes, but don't do it often, says Apple:

Although the Objective-C language currently allows you to use a category to override methods the class inherits, or even methods declared in the class interface, you are strongly discouraged from doing so. A category is not a substitute for a subclass. There are several significant shortcomings to using a category to override methods:

When a category overrides an inherited method, the method in the category can, as usual, invoke the inherited implementation via a message to super. However, if a category overrides a method that exists in the category's class, there is no way to invoke the original implementation.

A category cannot reliably override methods declared in another category of the same class.

This issue is of particular significance because many of the Cocoa classes are implemented using categories. A framework-defined method you try to override may itself have been implemented in a category, and so which implementation takes precedence is not defined.

The very presence of some category methods may cause behavior changes across all frameworks. For example, if you override the windowWillClose: delegate method in a category on NSObject, all window delegates in your program then respond using the category method; the behavior of all your instances of NSWindow may change. Categories you add on a framework class may cause mysterious changes in behavior and lead to crashes.

Other than that, your life is gonna get pretty hard without subclassing. Even the runtime way of doing this (overriding the IMP's) would involve "subclassing" (allocating a class pair).

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top