runtime-分类为什么不生成setter和getter
前言
前几天有人问我一个问题:为什么分类不能自动创建get set方法。老实说,笔者从来没有去思考过这个问题。于是这次通过代码实践跟runtime源码来探究这个问题。
准备工作
为了能减少输出类数据的代码工作,笔者基于NSObject的分类封装了一套代码
其中输出类实例变量的具体代码:
- (void)logIvarsWithExpReg: (NSString *)expReg customed: (BOOL)customed {
[NSObject kRecordOBJ];
unsigned int ivarCount;
Ivar * ivars = class_copyIvarList([self class], &ivarCount);
for (int idx = 0; idx < ivarCount; idx++) {
Ivar ivar = ivars[idx];
NSString * ivarName = [NSString stringWithUTF8String: ivar_getName(ivar)];
if (customed && [kOBJIvarNames containsObject: ivarName]) {
continue;
}
if (expReg && !kValidExpReg(ivarName, expReg)) {
continue;
}
printf("ivar: %s --- %s\n", NSStringFromClass([self class]).UTF8String, ivarName.UTF8String);
}
free(ivars);
}
+(void)kRecordOBJ采用dispatch_once的方式将NSObject存在的数据存储到三个数组中,用来排除父类的数据输出
类的属性
正常创建类
@interface Person: NSObject {
int _pId;
} @property (nonatomic, copy) NSString * name;
@property (nonatomic, assign) NSUInteger age; @end int main(int argc, char * argv[]) {
@autoreleasepool {
Person * p = [[Person alloc] init];
[p logCustomIvars];
[p logCustomMethods];
[p logCustomProperties];
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}运行结果:属性
name和age生成了对应的_propertyName的实例变量以及setter和getter
动态生成属性
age@implementation Person
@dynamic age; @end运行结果:缺少了
_age变量以及对应的setAge:和age方法
手动实现
setter/getter@implemetation Person
@dynamic age; - (void)setAge: (NSUInteger)age {}
- (NSUInteger)age { return 18; } @end输出结果:未生成
_age实例变量
手动实现
_pId的setter/getter@implemetation Person
@dynamic age; - (void)setAge: (NSUInteger)age {}
- (NSUInteger)age { return 18; } - (void)setPId: (int)pId { _pId = pId; }
- (int)pId { return _pId; } @end [p setValueForKey: @"pId"];运行结果:
KVC的访问会触发setter方法,_pId除了无法通过点语法访问外,其他表现与@property无异
通过上面的几段试验,可以得出@property的公式:
分类属性
分类中添加
weigh和height属性@interface Person (category) @property (nonatomic, assign) CGFloat weigh;
@property (nonatomic, assign) CGFloat height; @end运行结果:
weigh和height未生成实例变量以及对应的setter/getter,与@dynamic修饰的age表现一致
使用
@synthesize自动合成setter/getter方法时编译报错
手动实现
setter/getter
@implemetation Person (category)- (void)setWeigh: (CGFloat)weigh {}
- (CGFloat)weigh { return 150; } @end运行结果:与
@dynamic age后重写其setter/getter表现一致动态绑定属性来实现
setter/gettervoid * kHeightKey = &kHeightKey;
@implemetation Person (category) - (void)setWeigh: (CGFloat)weigh {}
- (CGFloat)weigh { return 150; } - (void)setHeight: (CGFloat)height {
objc_setAssociatedObject(self, kHeightKey, @(height), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (CGFloat)height {
return return [objc_getAssociatedObject(self, kHeightKey) doubleValue];;
} @end [p logCustomIvars]
[p logCustomMethods];
[p logCustomProperties]; CGFloat height = 180;
p.height = 180;
height = p.height; [p logCustomIvars]
[p logCustomMethods];
[p logCustomProperties];运行结果:动态绑定前后
ivar没有发生任何变化
通过代码实验,可以得出下面两个结论:
- 分类属性相当于
@dynamic property - 缺少
ivar的情况下无法使用@synthesize自动合成属性
以及一个猜想:
- 在类完成加载后无法继续添加
ivar
通过runtime动态创建类验证猜想:
int main(int argc, char * argv[]) {
NSString * className = @"Custom";
Class customClass = objc_allocateClassPair([NSObject class], className.UTF8String, 0);
class_addIvar(customClass, @"ivar1".UTF8String, sizeof(NSString *), 0, "@");
objc_property_attribute_t type1 = { "T", "@\"NSString\"" };
objc_property_attribute_t ownership1 = { "C", "N" };
objc_property_attribute_t atts1[] = { type1, ownership1 };
class_addProperty(customClass, "property1", atts1, 2);
objc_registerClassPair(customClass);
id instance = [[customClass alloc] init];
NSLog(@"\nLog Ivars ===================");
[instance logCustomIvars];
NSLog(@"\nLog methods ===================");
[instance logCustomMethods];
NSLog(@"\nLog properties ===================");
[instance logCustomProperties];
class_addIvar(customClass, @"ivar2".UTF8String, sizeof(NSString *), 0, "@");
objc_property_attribute_t type2 = { "T", "@\"NSString\"" };
objc_property_attribute_t ownership2 = { "C", "N" };
objc_property_attribute_t atts2[] = { type2, ownership2 };
class_addProperty(customClass, "property2", atts2, 2);
instance = [[customClass alloc] init];
NSLog(@"\nLog Ivars ===================");
[instance logCustomIvars];
NSLog(@"\nLog methods ===================");
[instance logCustomMethods];
NSLog(@"\nLog properties ===================");
[instance logCustomProperties];
}
运行结果:在调用class_registerClassPair后,添加ivar失败
从源码解析
objc_class的结构体定义如下:
struct objc_class : objc_object {
Class superclass;
const char *name;
uint32_t version;
uint32_t info;
uint32_t instance_size;
struct old_ivar_list *ivars;
struct old_method_list **methodLists;
Cache cache;
struct old_protocol_list *protocols;
// CLS_EXT only
const uint8_t *ivar_layout;
struct old_class_ext *ext;
}
ps: 在新版本中结构体内部已经发生了大改,但是内部的属性大致上仍是这些
这里面有个重要的属性ivar_layout,顾名思义存放的是变量的位置属性,与之对应的还有一个weakIvarLayout变量,不过在默认结构中没有出现。这两个属性用来记录ivar哪些是strong或者weak,而这个记录操作在runtime阶段已经被确定好。正由于如此,这极有可能是ivar无法在类被加载后继续添加的原因之一。ivar_layout的更多了解可以参照Objective-C Class Ivar layout一文
import操作帮助编译检查和链接过程,但是在category的加载过程中,不会将扩展的内容添加到原始的类结构中。runtime对于category的加载过程可以简单的分成下面几步(摘自objc category的密码):
objc runtime的加载入口是一个叫_objc_init的方法,在library加载前由libSystem dyld调用,进行初始化操作- 调用
map_images方法将文件中的imagemap到内存 - 调用
_read_images方法初始化map后的image,这里面干了很多的事情,像load所有的类、协议和category,著名的+ load方法就是这一步调用的
-仔细看category的初始化,循环调用了_getObjc2CategoryList方法,这个方法拿出来看看: - .…
这一切的过程发生在_objc_init函数中,函数实现如下
简单来说在load_images函数中最终会走到下面的代码调用来加载所有的类以及类的分类
根据上面的代码加上runtime的加载顺序,可以继续推出:
@dynamic实际上是将属性的加载推迟到类加载完成后
另外,前面也说过在缺少ivar的情况下无法自动合成setter/getter,除了category本身是不被添加到类结构中的,所以无法使用类结构的ivar合成属性外,还有分类自身结构的问题
struct category_t {
const char *name; /// 类名
classref_t cls; /// 类指针
struct method_list_t *instanceMethods; /// 实例方法
struct method_list_t *classMethods; /// 类方法
struct protocol_list_t *protocols; /// 扩展的协议
struct property_list_t *instanceProperties; /// 扩展属性
method_list_t *methodsForMeta(bool isMeta) { ... }
property_list_t *propertiesForMeta(bool isMeta) { ... }
};
可以看到分类结构本身是不存在ivar的容器的,因此缺少了自动合成属性的条件。最后还有一个问题,我们在使用objc_associate系列函数绑定属性的时候这些变量存储在了哪里?
总结
首先,iOS的分类在runtime实现的结构体中并不存在Ivar类型的容器,缺少了自动合成setter以及getter的必要条件,因此在分类中声明的属性默认为@dynamic修饰。
其次,OC本身是一门原型语言,对象和类原型很像。类对象执行alloc方法就像是原型模式中的copy操作一样,类保存了copy所需的实例信息,这些信息内存信息在runtime加载时就被固定了,没有扩充Ivar的条件。(感谢大表哥的科普)
最后,在runtime中存在一个类型为AssociationHashMap的哈希映射表保存着对象动态添加的属性,每个对象以自身地址为key维护着一个绑定属性表,我们动态添加的属性就都存储在这个表里,这也是动态添加property能成功的基础。
作者:sindri的小巢
链接:http://www.jianshu.com/p/dcc3284b65bf
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
runtime-分类为什么不生成setter和getter的更多相关文章
- 【原】iOS 同时重写setter和getter时候报错:Use of undeclared identifier '_name';did you mean 'name'
写了那么多的代码了,平时也没有怎么注意会报这个错误,因为平时都很少同时重写setter和getter方法,一般的话,我们大概都是使用懒加载方法,然后重写getter方法,做一个非空判断.然后有时候根据 ...
- 如果将synthesize省略,语义特性声明为assign retain copy时,自己实现setter和getter方法
如果将synthesize省略,并且我们自己实现setter和getter方法时,系统就不会生成对应的setter和getter方法,还有实例变量 1,当把语义特性声明为assign时,setter和 ...
- 假设将synthesize省略,语义特性声明为assign retain copy时,自己实现setter和getter方法
假设将synthesize省略,而且我们自己实现setter和getter方法时,系统就不会生成相应的setter和getter方法,还有实例变量 1,当把语义特性声明为assign时,setter和 ...
- 假设synthesize省略,语义属性声明assign retain copy时间,为了实现自己的setter和getter方法
假设synthesize省略,而且我们自己实现setter和getter方法时,系统就不会生成相应的setter和getter方法,还有实例变量 1,当把语义特性声明为assign时,setter和g ...
- Lombok的@Data、@Setter、@Getter注解没反应问题解决
在用@Data注解时,没有生成setter/getter方法.百度了一堆都没解决方法,后来用Google查了一下解决了~~~ 使用IDEA需要安装Lombok插件,我这里已经下载好,如果没下载安装点击 ...
- 自定义类属性设置及setter、getter方法的内部实现
属性是可以说是面向对象语言中封装的一个体现,在自定义类中设置属性就相当于定义了一个私有变量.设置器(setter方法)以及访问器(getter方法),其中无论是变量的定义,方法的声明和实现都是系统自动 ...
- iOS开发核心语言Objective C —— 面向对象思维、setter和getter方法及点语法
本分享是面向有意向从事iOS开发的伙伴们.或者已经从事了iOS的开发人员.假设您对iOS开发有极高的兴趣,能够与我一起探讨iOS开发.一起学习,共同进步.假设您是零基础,建议您先翻阅我之前分享的iOS ...
- setter 和 getter 高级 以及内存管理初级
setter 和 getter 的演变,紧接setter 和 getter 初级 1.@property 和 @synthesize 这两个关键字的出现,就是为了剔除代码中的setter方法和get ...
- 关于setter 和 getter方法的一些总结(初级)
1.最基础的set 和 get 准备工作 Person.h @interface Person : NSObject { NSString *_hobby; // ObjC建议成员变量带"_ ...
随机推荐
- UIScrollView翻书效果
代码地址如下:http://www.demodashi.com/demo/12695.html 前言:看到凤凰新闻 头条栏目的编辑推荐新闻是这个效果,觉得不错,就想着实现一下,以下就是我的实现过程. ...
- IDEA下配置Spring Boot的热部署
© 版权声明:本文为博主原创文章,转载请注明出处 devtools简介 spring-boot-devtools会监听classpath下的文件变动,并且会立即重启应用(发生在保存时机),因为其采用的 ...
- CSS3:选择器
CSS选择器的作用是找出某类元素,以便我们使用style元素或者外部样式表对这类元素设置样式. 基本选择器 选择器 含义 演示样例 描写叙述 * 选择全部元素 * { border: thin bla ...
- pycharm下: conda installation is not found ----一个公开的bug的解决方案
pycharm conda installation is not found ----一个公开的bug的解决方案 pycharm+anaconda 是当前的主流的搭建方案,但是常出现上述问题. ...
- 在Eclipse中使用JUnit4进行单元测试(初级篇、中级篇、高级篇)
本文转载自以下 初级篇: http://blog.csdn.net/andycpp/article/details/1327147 中级篇: http://blog.csdn.net/andycpp/ ...
- NYOJ 492 King (状态压缩)
做题感悟:做完这题发现状态压缩有很多须要优化的地方. 解题思路:状态压缩 開始自己用的一般的思路,就和炮兵阵地,郑厂长等题类似的方法做的,開始超时,然后把数组开到了最小的极限就险过.然后看了别人的代码 ...
- Docker-Compose 自动创建的网桥与局域网冲突解决方案
环境: 使用docker-compose.yml 部署应用,docker 默认的网络模式是bridge ,默认网段是172.17.0.1/16 ,不巧的是我们局域网也使用的172.22. xx 网段 ...
- Centos7 install RabbitMQ
安装rabbitmq 需要环境上有erlang,没有安装的可以参照下面的内容进行安装: https://www.erlang-solutions.com/resources/download.html ...
- GreenDao学习
官方文档地址:http://greenrobot.org/greendao/documentation//introduction/ 英语不好的可以使用谷歌翻译,很轻松的看懂文档,不需要FQ. 看不懂 ...
- python write file
fileHandle = open ( 'test.txt', 'a' ) fileHandle.write ( '\n\nBottom line.' ) fileHandle.close() 转自: ...