我想在运行时添加一个属性实现方法。添加我使用+ resolveInstanceMethod,class_addMethod来做。但在代码下面,在dynamicN()和dynamicSetN()中,它们不能被编译,我不知道如何使用C函数来设置/获取实例变量而不合成属性。如何生成动态属性getter/setter?
#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, "[email protected]:");
//return YES;
}
if (aSEL == @selector(setN:)) {
class_addMethod([self class], aSEL, (IMP) dynamicSetN, "[email protected]: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;
}
请添加您从编译器获得的错误消息。 – 2012-01-10 18:51:42