我正在尝试使用反射来覆盖我的属性的 getter 方法并创建延迟初始化。我该怎么做?
// 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;
}
上面是功能的实现,下面是使用
@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]
}
最佳答案
你似乎采用了一种奇怪的模式,我不禁认为你想要实现的可能是通过一些更高级别的路线更好地完成,例如:
if(result) return result;
/* stuff to fill result and then return it here */
分支预测应该可以忽略不计的运行时成本。
需要注意的是,您感兴趣的是 method_setImplementation (为方法设置 IMP),class_getMethodImplementation (从类和选择器中获取 IMP)和 class_getInstanceMethod (从类和选择器中获取方法)。使用这些,您可以设置给定方法以在运行时响应您想要的任何一个或多个选择器。
NSObject 提供了一些方便的方法来获取 IMP 和 Method,但它们并没有变得更短。
关于objective-c - Objective-C - 反射和覆盖方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6615188/