Cocoa, NSProxy, How to take over a method in an object?

906 Views Asked by At

I need to replace a method in an object with my own implementation. For example,

Person *p; // some object
NSMutableArray *array = [NSMutableArray array];
[array addObject: p];

How can I replace addObject with a method of my own?

In other words, is there a way to replace the implementation of addObject: of a SPECIFIC object with another implementation?

I have been playing around with NSProxy but couldnt find out what I should do.

Any help will be highly appreciated.

Thanks

3

There are 3 best solutions below

5
On

Make that object an instance of a different class with a different implementation for the method.

2
On

You could use a category to override the :addObject method of NSMutableArray. See the Learn Objective-C tutorial (section 11) for more information.

0
On

You can use method swizzling approach for replacing methods runtime. There was actually a question as yours on SO, I think the finsl solution should work for you also - Method swizzling for NSArray