iOS从UI内存地址到读取成员变量(oc/swift)

开发调试时,我们发现bug时常首先是从UI显示发现异常,下一步才会去定位UI相关连的数据的。XCode有给我们提供一系列debug工具,但是很多人可能还没有形成一套稳定的调试流程,因此本文尝试解决这个问题,顺便提出一个暴论:UI显示异常问题只需要两个步骤就能完成定位工作的80%:

  1. 定位异常 UI 组件的内存地址。
  2. 利用内存地址读取其成员变量。

定位异常UI组件内存地址

查看UI组件内存的方法还是蛮简单的,这里简单介绍。Xcode有提供可视化的UI查看工具:“Debug View Herarchy”,查看右侧辅助栏第四个选项(键盘快捷键cmd+opt+4)。

感兴趣的还可以去了解LookinchiselHMLLDB,不管哪一个,用起来都比那个基佬的Xcode稳定多了(阴阳怪气)。

读取成员变量

这里提出的解决方案是利用LLDB读取,当然二者使用上是存在差异的。

oc篇

暂停程序(cmd+ctrl+y)之后,拿到内存地址,然后:

// 内存地址为0x126708060
po ((ViewController *)(0x126708060)).ocString
// hello world

如果想读取多个变量,可以缩写:

// 内存地址为0x126708060
expr ViewController *$ocPage = (ViewController *)(0x126708060)
po $ocPage.ocString
//hello world
po $ocPage.view
//<UIView: 0x13750b930; frame = (0 0; 390 844); autoresize = W+H; backgroundColor = <UIDynamicSystemColor: 0x600001b5b080; name = systemBackgroundColor>; layer = <CALayer: 0x600000e761a0>>

如果是用chisel的话,可以用一个指令打印所有的成员变量

// 内存地址为0x126708060
po pinternals 0x126708060
/*
(ViewController) $7 = {
 UIViewController = {
 UIResponder = {
 NSObject = {
 isa = ViewController
 }
 }
 _overrideTransitioningDelegate = nil
 _view = 0x000000013750b930
 ...
 _ocString = 0x0000000100eac060 @"hello world"
}
*/

swift篇

暂停程序(cmd+ctrl+y)之后,拿到内存地址,接下来要做的则十分重要,你需要先输入类似于引用的指令(在这里踩坑踩到头皮发麻):

//避免出现报错 error: <user expression 2>:1:1: unknown type name 'let'
settings set target.language swift
//避免出现报错 error: <EXPR>:3:43: error: cannot find 'xxxx' in scope
expr import xxxx
//样例中则是 expr import HelloSwift

之后的和oc类似,只是语法比较贴近swift的格式:

// 内存地址0x125e0aae0,类型为HelloSwift.ViewController
expr let $swiftVc = unsafeBitCast(0x125e0aae0, to: HelloSwift.ViewController.self)
po $swiftVc.swiftString
//"Mr_Yu4"

总结

快速定位异常的道路上需要做的工作依然还有很多,lldb会是解决这个问题的重要工具,但是这个工具的学习曲线十分陡峭,所以平时没事的时候,记得在lldb里面多执行这个指令:

help
/*
Debugger commands:
 apropos -- List debugger commands related to a word or subject.
 breakpoint -- Commands for operating on breakpoints (see 'help b' for
 shorthand.)
 ....
*/
作者:MrYu4原文地址:https://www.cnblogs.com/MrYU4/p/ios-congui-nei-cun-de-zhi-dao-du-qu-cheng-yuan-bia.html

%s 个评论

要回复文章请先登录注册