Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSProxy vs NSObject

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

  • Checking if the required object for this method call was in the cache
  • If the cache had that object return it.
  • If not, dispatch to the original implementation, populate the cache and return that.

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?

like image 822
Jasper Blues Avatar asked Aug 17 '13 03:08

Jasper Blues


People also ask

What is Nsproxy?

An abstract superclass defining an API for objects that act as stand-ins for other objects or for objects that don't exist yet.

How do I create an NSObject in Objective C?

Creating a Custom ClassGo ahead an choose “Objective-C class” and hit Next. For the class name, enter “Person.” Make it a subclass of NSObject. NSObject is the base class for all objects in Apple's developer environment. It provides basic properties and functions for memory management and allocation.


1 Answers

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.

like image 190
Ken Thomases Avatar answered Sep 20 '22 17:09

Ken Thomases