【发布时间】:2012-07-31 01:46:15
【问题描述】:
我试图在运行时获取一个方法,然后使用它的数据结构来调用它的实现。澄清一下,这是出于学习目的,而不是出于任何实际原因。所以这是我的代码。
#import <Foundation/Foundation.h>
#import <stdio.h>
#import <objc/runtime.h>
@interface Test : NSObject
-(void)method;
@end
@implementation Test
-(void)method {
puts("this is a method");
}
@end
int main(int argc, char *argv[]) {
struct objc_method *t = (struct objc_method*) class_getInstanceMethod([Test class], @selector(method));
Test *ztest = [Test new];
(t->method_imp)(ztest, t->method_name);
[ztest release];
return 0;
}
struct objc_method的定义如下(在objc/runtime.h中定义)
typedef struct objc_method *Method;
....
struct objc_method {
SEL method_name OBJC2_UNAVAILABLE;
char *method_types OBJC2_UNAVAILABLE;
IMP method_imp OBJC2_UNAVAILABLE;
} OBJC2_UNAVAILABLE;
但是,当我尝试编译我的代码时,我得到了这个错误。
error: dereferencing pointer to incomplete type
但是当我将它添加到我的代码中(以显式声明一个 objc_method)时,它会按预期工作。
struct objc_method {
SEL method_name;
char *method_types;
IMP method_imp;
};
typedef struct objc_method* Method;
谁能向我解释为什么我的代码在我明确声明这个结构时有效,而不是当我从 objc/runtime.h 导入它时?它与 OBJC2_UNAVAILABLE 有什么关系吗?我找不到它的定义,但它是在我的环境中定义的。
编辑:
我运行gcc -E code.m -o out.m 来查看 OBJC2_UNAVAILABLE 被替换为什么,结果发现 OBJC2_UNAVAILABLE 在我的环境中被定义为 __attribute__((unavailable)) 。有人能解释一下这是什么意思吗?如果这个结构“不可用”,为什么Method 仍然有效?
【问题讨论】:
标签: objective-c data-structures methods objective-c-runtime