views:

34

answers:

2

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

A: 

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

Chuck
It is partially correct, however, what happens to other objects having a reference to this object? Doesnt it create dangling references?This change should be transparent to other objects.
Abbas
A: 

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

jsumners
Overriding methods in categories is really not recommended, plus this would replace the method for *all* instances of `NSMutableArray`, not just the single instance as desired.
jbrennan
What if I need to take over the whole object while being able to undo this replacement at any time in future?Furthermore, I need this change to be completely transparent to other objects having a reference to this object.As jbrennan pointed out, I need to do it for some specific objects.
Abbas