赞
踩
Runtime是iOS中比较难以理解, 但又非常强大的技术.
The Objective-C language defers as many decisions as it can from compile time and link time to runtime. Whenever possible, it does things dynamically. This means that the language requires not just a compiler, but also a runtime system to execute the compiled code. The runtime system acts as a kind of operating system for the Objective-C language; it’s what makes the language work.
所谓运行时, 就是尽可能地把决定从编译器推迟到运行期, 就是尽可能地做到动态. 只是在运行的时候才会去确定对象的类型和方法的. 因此利用Runtime机制可以在程序运行时动态地修改类和对象中的所有属性和方法.
Objective-C中调用对象的方法时, 会向该对象发送一条消息, runtime根据该消息做出反应.
Runtime是一套比较底层的纯C语言的API, Objective-C是运行在Runtime上的, 因此在Runtime中动态添加和实现一些非常强大的功能也就不足为奇了.
在Objective-C代码中使用Runtime, 需要引入
#import <objc/runtime.h>
OC中类和对象的实例变量, 实际上是一个指向objc_ivar结构体的指针Ivar.
/// An opaque type that represents an instance variable.
typedef struct objc_ivar *Ivar;
通过runtime方法class_copyIvarList可获取一个指向类和对象的所有实例变量的Ivar指针.
u_int count = 0;
Ivar *ivars = class_copyIvarList([UIView class], &count);
for (int i = 0; i < count; i++) {
const char *ivarName = ivar_getName(ivars[i]);
NSString *str = [NSString stringWithCString:ivarName encoding:NSUTF8StringEncoding];
NSLog(@"ivarName : %@", str);
}
获取到实例变量的Ivar指针后, 即可通过ivar_getName方法获取该实例变量的名称, 由C语言的字符串表示.
部分打印结果如下:
ivarName : _constraintsExceptingSubviewAutoresizingConstraints ivarName : _cachedTraitCollection ivarName : _layer ivarName : _layerRetained ivarName : _gestureInfo ivarName : _gestureRecognizers ivarName : _subviewCache ivarName : _templateLayoutView ivarName : _charge ivarName : _tag ivarName : _viewDelegate ivarName : _backgroundColorSystemColorName ivarName : _countOfMotionEffectsInSubtree ivarName : _countOfTraitChangeRespondersInDirectSubtree ivarName : _cachedScreenScale ivarName : _viewFlags ivarName : _retainCount
可以看到, 其中包含了UIView中的很多我们经常使用的实例变量.
对于属性, 如layer, tag等, 会自动生成 _ 前缀的成员变量
OC
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。