Isaaс Weisberg
Isaaс Weisberg

Reputation: 2814

How to dynamically set a getter for an Objective-C object property?

FooClass has a property called foo.

It's declared as @property (nullable, nonatomic, readonly, strong) id foo and it has NO underlying storage, it's not synthesized. It's just a getter that by default returns nil.

I would like to change the implementation of this getter. I would like to create a new block/function and inject it into an object so that it replaces the original implementation.

IMPORTANT: subclassing is NOT an option. I need to take the object as is.

ALSO: I need to do it for only one, single instance, not the whole class!

How can I do it?

Upvotes: 0

Views: 53

Answers (1)

jacorl
jacorl

Reputation: 552

This is a generic response why not using the delegate pattern ?

  • Add a delegate object for your class

Override Property getter

- (id)foo {
  if (delegate) { 
    [self performSelector:@Selector(someMethod) withObject:nil];
  }
  return nil;
}

When you want to change the method purpose set the delegate and provide your custom method impl...

Hardcore (not rec)

You can achieve this by using method swizzling in Objective-C. Swizzling involves swapping the implementation of methods at runtime

Upvotes: 0

Related Questions