Category

Category

  • 实现原理

    • Category编译之后是一个结构体struct category_t,里边存储着分类的对象方法、类方法、属性、协议信息
    • 在程序运行的时候,runtime会将Category的数据,合并到类信息中(类对象,元类对象)
  • Category和Class Extension的区别

    • Class Extension在编译的时候,他的数据就已经包含在类信息中
    • Category是在运行时,才会将数据合并到类信息中
  • Category添加的实例方法是存储在其对应的类对象里,类方法存储在其对应的元类对象里

  • Category添加的方法是在runtime过程中动态添加的

  • Category编译完成后结构

  • 多个分类

int mcount = 0;
int i = cats->count; // cats 为分类数组
while (i--) {
	auto& entry = cats->list[i];
	method_list_t *mlist = entry.cat->methodsFoMeta(isMeta);
	
	mlists[mcount++] = mlist;
	
	// 后编译的分类方法先取出来添加到方法
	// ...
}

struct _category_t {
	const char *name;
	struct  _class_t *cls;
	const struct _method_list_t *instance_methods;
	const struct _method_list_t *class_methods;
	const struct _protocol_list_t *protocols;
	const struct _prop_list_t *properties;
};
  • objc-runtime-old
void attachList(List* const * addedLists, uint32_t addedCount) {
	if (addedCount == 0) return;
	if (haveArray()) {
		uint32_t oldCount = array()->count;
		uint32_t newCount = oldCount + addedCount;
		setArray((array_t *)realloc(array(), array_t::byteSize(newCount)));
		array()->count = newCount;
		memmove(array()->lists, addedLists, addedCount * sizeof(array()->lists[0]));
		memcopy(array()->lists, addedLists, addedCount * sizeof(array()->lists[0]));
	}

}

  • objc-runtime-new
void attachLists(List* const * addedLists, uint32_t addedCount) {
	if (addedCount == 0) return;
	
	if (hasArray()) {
	  // many lists -> many lists
	  uint32_t oldCount = array()->count;
	  uint32_t newCount = oldCount + addedCount;
	  array_t *newArray = (array_t *)malloc(array_t::byteSize(newCount));
	  newArray->count = newCount;
	  array()->count = newCount;
	
	  for (int i = oldCount - 1; i >= 0; i--)
	      newArray->lists[i + addedCount] = array()->lists[i];
	  for (unsigned i = 0; i < addedCount; i++)
	      newArray->lists[i] = addedLists[i];
	  free(array());
	  setArray(newArray);
	  validate();
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值