您的位置:首页 > 移动开发 > Objective-C

Objective-C Runtime 运行时(4)

2017-12-20 00:33 387 查看
Objective-C中可以通过category给一个类添加方法扩充它,但不能添加实例变量。还可以通过@protocol定义接口,@protocol声明的方法后由其它类负责实现。

Category是一个指向分类结构体的指针,定义如下:

typedef struct objc_category *Category;
struct objc_category {
char *category_name                          OBJC2_UNAVAILABLE; // 分类名
char *class_name                             OBJC2_UNAVAILABLE; // 分类所属的类名
struct objc_method_list *instance_methods    OBJC2_UNAVAILABLE; // 实例方法列表
struct objc_method_list *class_methods       OBJC2_UNAVAILABLE; // 类方法列表
struct objc_protocol_list *protocols         OBJC2_UNAVAILABLE; // 分类所实现的协议列表
}


Protocol定义如下:

typedef struct objc_object Protocol;


可以看出Protocol其中实就是一个对象结构体。所以协议可以定义方法,属性,成员变量。具有多继承的特点。

@interface RuntimeCategoryClass (Category)
- (void)categoryMethod;
@end
@interface RuntimeCategoryClass : NSObject

@end
unsigned int outCount = 0;
Method *methodList = class_copyMethodList(RuntimeCategoryClass.class, &outCount);
for (int i = 0; i < outCount; i++) {
Method method = methodList[i];
const char *name = sel_getName(method_getName(method));
NSLog(@"RuntimeCategoryClass's method: %s", name);
if (strcmp(name, sel_getName(@selector(method2)))) {
NSLog(@"分类方法categoryMethod在objc_class的方法列表中");
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息