iOS --- 理解Runtime机制及其使用场景

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

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值