YYModel 源码解读(二)之YYClassInfo.h (2)
/**
Instance variable information.
*/
@interface YYClassIvarInfo : NSObject
@property (nonatomic, assign, readonly) Ivar ivar; ///< ivar opaque struct
@property (nonatomic, strong, readonly) NSString *name; ///< Ivar's name
@property (nonatomic, assign, readonly) ptrdiff_t offset; ///< Ivar's offset
@property (nonatomic, strong, readonly) NSString *typeEncoding; ///< Ivar's type encoding
@property (nonatomic, assign, readonly) YYEncodingType type; ///< Ivar's type /**
Creates and returns an ivar info object. @param ivar ivar opaque struct
@return A new object, or nil if an error occurs.
*/
- (instancetype)initWithIvar:(Ivar)ivar;
@end
上边代码通过创建Ivar(成员变量)的 抽象类, 返回我们需要的关于Ivar 的信息,
通过一个初始化方法创建,接下来我们看看该方法的具体实现
- (instancetype)initWithIvar:(Ivar)ivar {
// 初始化判空 如果为空 就返回nil
if (!ivar) return nil;
self = [super init];
_ivar = ivar; // 获取成员变量的名称
const char *name = ivar_getName(ivar);
if (name) { // 把c的字符串转化成oc的字符串
_name = [NSString stringWithUTF8String:name];
} _offset = ivar_getOffset(ivar); // 获取类型编码
const char *typeEncoding = ivar_getTypeEncoding(ivar);
if (typeEncoding) { // 转为oc的字符穿
_typeEncoding = [NSString stringWithUTF8String:typeEncoding]; // 转成枚举值
_type = YYEncodingGetType(typeEncoding); }
return self;
}
ivar_getName
ivar_getTypeEncoding
ivar_getOffset 这三个方法都是运行时方法,分别用来获取 名称 , 类型编码 , 偏移量 尤其要之处的是
ivar_getOffset方法: 官方文档中的描述是这样的
Returns the offset of an instance variable. Declaration
ptrdiff_t ivar_getOffset( Ivar ivar)
Discussion
For instance variables of type id or other object types, call object_getIvar and object_setIvar instead of using this offset to access the instance variable data directly.
ivar_getOffset函数,对于类型id或其它对象类型的实例变量,可以调用object_getIvar和object_setIvar来直接访问成员变量,而不使用偏移量。
接下来我们看看Method(方法)的 抽象类
/**
Method information.
*/
@interface YYClassMethodInfo : NSObject
@property (nonatomic, assign, readonly) Method method; ///< method opaque struct
@property (nonatomic, strong, readonly) NSString *name; ///< method name
@property (nonatomic, assign, readonly) SEL sel; ///< method's selector
@property (nonatomic, assign, readonly) IMP imp; ///< method's implementation
@property (nonatomic, strong, readonly) NSString *typeEncoding; ///< method's parameter and return types
@property (nonatomic, strong, readonly) NSString *returnTypeEncoding; ///< return value's type
@property (nullable, nonatomic, strong, readonly) NSArray<NSString *> *argumentTypeEncodings; ///< array of arguments' type /**
Creates and returns a method info object. @param method method opaque struct
@return A new object, or nil if an error occurs.
*/
- (instancetype)initWithMethod:(Method)method;
@end
这这段代码中 比较陌生的是Method 和 IMP
Method 是一个结构体:
struct objc_method
1.方法名:方法名为此方法的方法签名,相同函数名和参数的方法名是一样的
{
SEL method_name;
char * method_types;
IMP method_imp;
};
2.方法类型: 描述方法的参数类型
3. 方法真实实现代码块的地址指针,可像C 一样直接调用
- (instancetype)initWithMethod:(Method)method {
if (!method) return nil;
self = [super init];
_method = method; // Method获取方法的名称
_sel = method_getName(method); // 方法的实现地址
_imp = method_getImplementation(method); // SEL 获取方法名
const char *name = sel_getName(_sel);
if (name) {
_name = [NSString stringWithUTF8String:name];
} // 获取类型
const char *typeEncoding = method_getTypeEncoding(method);
if (typeEncoding) {
_typeEncoding = [NSString stringWithUTF8String:typeEncoding];
} // 获取返回值类型
char *returnType = method_copyReturnType(method);
if (returnType) {
_returnTypeEncoding = [NSString stringWithUTF8String:returnType]; // 但凡 通过copy retain alloc 系统方法得到的内存,必须使用relea() 或 free() 进行释放
free(returnType);
} // 获取参数列表
unsigned int argumentCount = method_getNumberOfArguments(method);
if (argumentCount > ) { NSMutableArray *argumentTypes = [NSMutableArray new]; for (unsigned int i = ; i < argumentCount; i++) { // 获取参数中的某一个参数
char *argumentType = method_copyArgumentType(method, i); NSString *type = argumentType ? [NSString stringWithUTF8String:argumentType] : nil;
[argumentTypes addObject:type ? type : @""];
if (argumentType) free(argumentType);
}
_argumentTypeEncodings = argumentTypes;
}
return self;
}
上边的代码使用了运行时中 关于Method 的一些方法,再次不做介绍,但值得注意的是
但凡 通过copy retain alloc 系统方法得到的内存,必须使用relea() 或 free() 进行释放
/**
Property information.
*/
@interface YYClassPropertyInfo : NSObject
@property (nonatomic, assign, readonly) objc_property_t property; ///< property's opaque struct
@property (nonatomic, strong, readonly) NSString *name; ///< property's name
@property (nonatomic, assign, readonly) YYEncodingType type; ///< property's type
@property (nonatomic, strong, readonly) NSString *typeEncoding; ///< property's encoding value
@property (nonatomic, strong, readonly) NSString *ivarName; ///< property's ivar name
@property (nullable, nonatomic, assign, readonly) Class cls; ///< may be nil
@property (nonatomic, assign, readonly) SEL getter; ///< getter (nonnull)
@property (nonatomic, assign, readonly) SEL setter; ///< setter (nonnull) /**
Creates and returns a property info object. @param property property opaque struct
@return A new object, or nil if an error occurs.
*/
- (instancetype)initWithProperty:(objc_property_t)property;
上边的类是对属性的抽象类,让我们通过下边的代码 了解下属性编码的知识
objc_property_t property = class_getProperty([YYWeiboStatus class], "user"); unsigned int num;
objc_property_attribute_t *attr = property_copyAttributeList(property, &num);
for (unsigned int i = ; i < num; i++) { objc_property_attribute_t att = attr[i];
fprintf(stdout, "name = %s , value = %s \n",att.name , att.value);
} const char *chars = property_getAttributes(property);
fprintf(stdout, "%s \n",chars);
打印的输出结果为
name = T , value = @"YYWeiboUser"
name = & , value =
name = N , value =
name = V , value = _user
T@"YYWeiboUser",&,N,V_user
可以看出,比较重要的是属性的编码都是以T开头 标示属性的类型 以V开头 标示属性的变量名
- (instancetype)initWithProperty:(objc_property_t)property {
if (!property) return nil;
self = [self init]; _property = property; // 1. 获取属性名称
const char *name = property_getName(property);
if (name) {
_name = [NSString stringWithUTF8String:name];
} // 2.获取每一个属性的编码字符串
YYEncodingType type = ;
unsigned int attrCount;
objc_property_attribute_t *attrs = property_copyAttributeList(property, &attrCount); // 3. 编译每一个属性的 objc_property_attribute_t
for (unsigned int i = ; i < attrCount; i++) { // 3.1 根据objc_property_attribute_t 中的name 做一些事
switch (attrs[i].name[]) { // T 代码属性的类型编码
case 'T': { // Type encoding
if (attrs[i].value) {
_typeEncoding = [NSString stringWithUTF8String:attrs[i].value];
type = YYEncodingGetType(attrs[i].value); // 计算属性的实体类型 比如:@"User"
if ((type & YYEncodingTypeMask) == YYEncodingTypeObject) { size_t len = strlen(attrs[i].value); // len = 7
if (len > ) {
char name[len - ]; // 新建一个长度 = len - 2 的name字符数组 长度为5
name[len - ] = '\0'; // 设置最后一个字符为\0
memcpy(name, attrs[i].value + , len - ); // copy USer 到name 中, // 获取name 的真实实体类型
_cls = objc_getClass(name);
}
}
}
} break;
case 'V': { // Instance variable
if (attrs[i].value) {
_ivarName = [NSString stringWithUTF8String:attrs[i].value];
}
} break;
case 'R': {
type |= YYEncodingTypePropertyReadonly;
} break;
case 'C': {
type |= YYEncodingTypePropertyCopy;
} break;
case '&': {
type |= YYEncodingTypePropertyRetain;
} break;
case 'N': {
type |= YYEncodingTypePropertyNonatomic;
} break;
case 'D': {
type |= YYEncodingTypePropertyDynamic;
} break;
case 'W': {
type |= YYEncodingTypePropertyWeak;
} break;
case 'G': { // getter 方法
type |= YYEncodingTypePropertyCustomGetter;
if (attrs[i].value) {
_getter = NSSelectorFromString([NSString stringWithUTF8String:attrs[i].value]);
}
} break;
case 'S': { // setter 方法
type |= YYEncodingTypePropertyCustomSetter;
if (attrs[i].value) {
_setter = NSSelectorFromString([NSString stringWithUTF8String:attrs[i].value]);
}
} // break; commented for code coverage in next line
default: break;
}
}
if (attrs) {
free(attrs);
attrs = NULL;
} _type = type; // 获取setter 和 getter 方法
if (_name.length) {
if (!_getter) {
_getter = NSSelectorFromString(_name);
}
if (!_setter) {
_setter = NSSelectorFromString([NSString stringWithFormat:@"set%@%@:", [_name substringToIndex:].uppercaseString, [_name substringFromIndex:]]);
}
}
return self;
}
最后让我来看看打印结果
objc_property_t property = class_getProperty([YYWeiboStatus class], "user"); YYClassPropertyInfo *propertyInfo = [[YYClassPropertyInfo alloc] initWithProperty:property]; NSLog(@"%@",propertyInfo.typeEncoding);
-- ::12.134 ModelBenchmark[:] @"YYWeiboUser"
typedef struct example {
int* aPint;
double aDouble;
char *aString;
int anInt;
BOOL isMan;
struct example *next;
} Example;
@property (nonatomic, assign) Example example;
-- ::59.493 ModelBenchmark[:] {example=^id*iB^{example}}
objc_property_t property = class_getProperty([YYWeiboStatus class], "statusID"); YYClassPropertyInfo *propertyInfo = [[YYClassPropertyInfo alloc] initWithProperty:property]; NSLog(@"%@",propertyInfo.typeEncoding);
-- ::39.747 ModelBenchmark[:] Q
到此 关于 Ivar Method Property 的抽象类已经介绍完毕,在后面的使用中 直接使用这些抽象类来进行编码的
YYModel 源码解读(二)之YYClassInfo.h (2)的更多相关文章
- YYModel 源码解读(二)之NSObject+YYModel.h (1)
本篇文章主要介绍 _YYModelPropertyMeta 前边的内容 首先先解释一下前边的辅助函数和枚举变量,在写一个功能的时候,这些辅助的东西可能不是一开始就能想出来的,应该是在后续的编码过程中 ...
- jQuery.Callbacks 源码解读二
一.参数标记 /* * once: 确保回调列表仅只fire一次 * unique: 在执行add操作中,确保回调列表中不存在重复的回调 * stopOnFalse: 当执行回调返回值为false,则 ...
- (转)go语言nsq源码解读二 nsqlookupd、nsqd与nsqadmin
转自:http://www.baiyuxiong.com/?p=886 ---------------------------------------------------------------- ...
- YYModel 源码解读(二)之YYClassInfo.h (3)
前边3篇介绍了YYClassinfo 文件的组成单元,算是功能的分割,按照业务的设计思想来说,方向应该是相反的 由此引申出我们在设计api的思想其实和项目管理是很类似的----- 一些题外话 1.目的 ...
- YYModel 源码解读(一)之YYModel.h
#if __has_include(<YYModel/YYModel.h>) FOUNDATION_EXPORT double YYModelVersionNumber; FOUNDATI ...
- YYModel 源码解读 总结
在使用swfit写代码的过程中,使用了下oc写的字典转模型,发现有些属性转不成功,就萌生了阅读源码的想法. 其实一直都知道Runtime机制,但并没有系统的学习,可能是因为平时的使用比较少,无意间在g ...
- ConcurrentHashMap源码解读二
接下来就讲解put里面的三个方法,分别是 1.数组初始化方法initTable() 2.线程协助扩容方法helpTransfer() 3.计数方法addCount() 首先是数组初始化,再将源码之前, ...
- mybatis源码解读(二)——构建Configuration对象
Configuration 对象保存了所有mybatis的配置信息,主要包括: ①. mybatis-configuration.xml 基础配置文件 ②. mapper.xml 映射器配置文件 1. ...
- ROS源码解读(二)--全局路径规划
博客转载自:https://blog.csdn.net/xmy306538517/article/details/79032324 ROS中,机器人全局路径规划默认使用的是navfn包 ,move_b ...
- go语言nsq源码解读二 nsqlookupd、nsqd与nsqadmin
nsqlookupd: 官方文档解释见:http://bitly.github.io/nsq/components/nsqlookupd.html 用官方话来讲是:nsqlookupd管理拓扑信息,客 ...
随机推荐
- Fis3的前端工程化之路[三大特性篇之内容嵌入]
Fis3版本:v3.4.22 Fis3的三大特性 资源定位:获取任何开发中所使用资源的线上路径 内容嵌入:把一个文件的内容(文本)或者base64编码(图片)嵌入到另一个文件中 依赖声明:在一个文本文 ...
- 微信应用号(小程序)开发IDE配置(第一篇)
2016年9月22日凌晨,微信宣布“小程序”问世,当然只是开始内测了,微信公众平台对200个服务号发送了小程序内测邀请.那么什么是“小程序”呢,来看微信之父怎么说 看完之后,相信大家大概都有些明白了吧 ...
- LeetCode: 3Sum
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all un ...
- 【.net 深呼吸】程序集的热更新
当一个程序集被加载使用的时候,出于数据的完整性和安全性考虑,程序集文件(在99.9998%的情况下是.dll文件)会被锁定,如果此时你想更新程序集(实际上是替换dll文件),是不可以操作的,这时你得把 ...
- 【原】FMDB源码阅读(二)
[原]FMDB源码阅读(二) 本文转载请注明出处 -- polobymulberry-博客园 1. 前言 上一篇只是简单地过了一下FMDB一个简单例子的基本流程,并没有涉及到FMDB的所有方方面面,比 ...
- dubbo服务提供与消费
一.前言 项目中用到了Dubbo,临时抱大腿,学习了dubbo的简单实用方法.现在就来总结一下dubbo如何提供服务,如何消费服务,并做了一个简单的demo作为参考. 二.Dubbo是什么 Dubbo ...
- 如何优化coding
如何优化coding 前言 最近一直在做修改bug工作,修改bug花费时间最多的不是如何解决问题而是怎样快速读懂代码.如果代码写的好的,不用debug就可以一眼看出来哪里出了问题.实际上,我都要deb ...
- 防线修建 bzoj 2300
防线修建(1s 512MB)defense [问题描述] 近来A国和B国的矛盾激化,为了预防不测,A国准备修建一条长长的防线,当然修建防线的话,肯定要把需要保护的城市修在防线内部了.可是A国上层现在还 ...
- cocos2dx调用浏览器打开网址
安卓端cocos2dx/platform/android路径下CCApplication.h: virtual void openURL(const char* pszUrl); CCApplicat ...
- mysql5.x升级至mysql5.7后导入之前数据库date出错的解决方法!
mysql5.x升级至mysql5.7后导入之前数据库date出错的解决方法! 修改mysql5.7的配置文件即可解决,方法如下: linux版:找到mysql的安装路径进入默认的为/usr/shar ...