I am trying to use reflection to override the getter method for my properties and create lazy initialization. how can I do that?
// This should be a public method maybe a category to NSObject
- (void)overrideGetterMethod
{
//somehow convert my original getter with lazyInitialize method
}
- (id)lazyInitialize
{
if (!self)
{
self = [[self class] alloc] init];
}
return self;
}
Above is the implementation of the functionality, and below is the use of it
@property (nonatomic, retain) SomeObject *someObject;
- (void)viewDidLoad
{
[super viewDidLoad];
[someObject overrideGetterMethod];
// So when I call the following method if the object is nil it get's instantiated automatically
[self.someObject doSomething]
}
You seem to be adopting an odd pattern, and I can't help thinking that you want to achieve is probably better done by some higher level route, such as simply:
if(result) return result;
/* stuff to fill result and then return it here */
Branch prediction should give that a negligible runtime cost.
That caveat being stated, the things you're interested in are method_setImplementation (to set the IMP for a Method), class_getMethodImplementation (to get an IMP from a class and selector) and and class_getInstanceMethod (to get a Method from a class and selector). Using those, you can set a given method to respond to whatever selector or selectors you want at runtime.
NSObject provides some convenience methods for getting the IMP and the Method, but they don't end up being any shorter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With