我想在运行时添加一个属性实现方法。添加我使用+resolveInstanceMethod,class_addMethod来做。但在代码下方,在 dynamicN() 和 dynamicSetN() 中,它们无法编译,我不知道如何使用 C-Function 设置/获取没有合成属性的实例变量。
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
float dynamicN(id self, SEL _cmd)
{
NSString *methodName = NSStringFromSelector(_cmd);
NSLog(@"%@,%@", methodName, [self description]);
// return [self n];
}
void dynamicSetN(id self, SEL _cmd, float sname)
{
printf("setName start;\n");
// self.n = sname;
}
@interface bird : NSObject
{
int height;
float n;
}
@property float n;
@property int height;
@end
@implementation bird
@synthesize height = height;
@dynamic n;
- (id)init
{
if (self = [super init]) {
n = 1.0;
height = 3;
}
return self;
}
- (float) n {
return n;
}
+ (BOOL) resolveInstanceMethod:(SEL)aSEL
{
if (aSEL == @selector(n)) {
//class_addMethod([self class], aSEL, (IMP) dynamicN, "f@:");
//return YES;
}
if (aSEL == @selector(setN:)) {
class_addMethod([self class], aSEL, (IMP) dynamicSetN, "v@:f");
return YES;
}
return [super resolveInstanceMethod:aSEL];
}
@end
int main(int argc, const char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
bird *aBird = [[bird alloc] init];
aBird.n = 3;
printf("\n%f\n,%d", aBird.n, aBird.height);
[pool drain];
return 0;
}
最佳答案
@H2CO3 关于您的二传手是正确的。动态 setter/getter 具有相同的基本问题。您正在尝试调用 [self n]
,它在 id
上不存在。 这就是它无法编译的原因。(正如@H2CO3 指出的那样,这将生成警告,而不是错误;你们都在使用 -Werror
,对吧?)但是更重要的是,即使这样做了,这也将是一个无限循环。 self.n
只是对 [self n]
的调用,它将分派(dispatch)回此函数。
如果您正在寻找示例,可以下载 iOS 6 Programming Pushing the Limits 第 20 章的代码.在 Person
项目中查找 Person.m
。如果您有兴趣,第 28 章包含有关如何实现此类功能的更多解释。
请注意,在 ObjC 中正确命名非常重要。您的类应该是 Bird
,而不是 bird
。在尝试动态调度等高级功能之前,掌握命名基础知识至关重要。
关于objective-c - 如何生成动态属性getter/setter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8806971/