Jasper Blues
Jasper Blues

Reputation: 28776

NSProxy vs NSObject

I was using method swizzling to wrap all method invocations in a class with some extra functionality. Specifically I was:

For each method, I would reroute to an advised method. And implement the new method using + (BOOL)resolveInstanceMethod:(SEL)sel and IMP_implementationWithBlock.

It worked fine, but the code didn't read nicely. It seems NSProxy will provide a neater way to implement this functionality.

But still another alternative, would be to simply have an NSObject subclass stand-in and intercept method calls around my target object's methods. By overriding forwardInvocation and methodSignatureForSelector, I can get the required outcome.

So what does NSProxy give me? Why should I use this instead?

Upvotes: 20

Views: 4049

Answers (1)

Ken Thomases
Ken Thomases

Reputation: 90601

The point of NSProxy is that it doesn't implement most methods. That's necessary to be sure that the Objective-C forwarding machinery gets invoked to begin with. If you start with NSObject, there are a lot of methods which will just be directly dispatched without you having an opportunity to forward them.

Upvotes: 16

Related Questions