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

Abbas
  • 3,228
  • 1
  • 23
  • 27

3 Answers3

1

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

Chuck
  • 234,037
  • 30
  • 302
  • 389
  • 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 Jul 28 '10 at 00:39
  • Your class should be a subclass of `NSMutableArray`. It's transparent to other objects, which will can treat your `CustomizedArray` like any other mutable array. addObject will just behave a little differently, according to your implementation. – paulmelnikow Aug 19 '11 at 18:48
  • @noa: Subclassing NSMutableArray is not that simple. You'll have to reimplement the class's entire functionality if you do that. – Chuck Aug 19 '11 at 18:51
  • 1
    @noa: NSMutableArray is part of the NSArray class cluster. It exists primarily as an interface. All NSArrays and NSMutableArrays that you use are actually instances of a private NSMutableArray subclass. If you subclass NSMutableArray, you don't get any of the actual functionality because it's all in NSCFArray. – Chuck Aug 19 '11 at 19:04
  • Got it. Sounds like you need to reimplement it, then, or proxy it. Thanks! – paulmelnikow Aug 19 '11 at 19:14
0

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

Community
  • 1
  • 1
Nikita Leonov
  • 5,684
  • 31
  • 37
0

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

James Sumners
  • 14,485
  • 10
  • 59
  • 77
  • 3
    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 Jul 28 '10 at 00:39
  • 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 Jul 28 '10 at 00:42