JiandanDream


  • 首页

  • 归档

  • 分类

  • 关于

关于_Method_Swizzling_的一点思考

发表于 2019-02-13

写在前面

经典的实现例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#import <objc/runtime.h>

@implementation UIViewController (Tracking)

+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = [self class];

SEL originalSelector = @selector(viewWillAppear:);
SEL swizzledSelector = @selector(xxx_viewWillAppear:);

Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);

// 如果交换的是类方法,则使用以下代码:
// Class class = object_getClass((id)self);
// ...
// Method originalMethod = class_getClassMethod(class, originalSelector);
// Method swizzledMethod = class_getClassMethod(class, swizzledSelector);

BOOL didAddMethod =
class_addMethod(class,
originalSelector,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod));

if (didAddMethod) {
class_replaceMethod(class,
swizzledSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
});
}

#pragma mark - Method Swizzling

- (void)xxx_viewWillAppear:(BOOL)animated {
[self xxx_viewWillAppear:animated];
NSLog(@"viewWillAppear: %@", self);
}

@end

关于这个例子,笔者有几点疑问:

  1. 为什么可以交换?
  2. 为什么要在 load 方法里处理?
  3. 为什么不直接使用 method_exchangeImplementations 即可?

查找资料后,给出以下回答。

为什么可以交换?

Objc 中对象调用方法,被称为消息传递,其基本过程:

  1. 根据对象的 isa 指针,找到类。
  2. 在类的 objc_cache 和 method_list 中,根据 method name 寻找对应方法。
  3. 若没有找到,则在其父类中寻找,直到 NSObject。
  4. 若是在 NSObject 中没有找到,则触发消息转发机制;若找到,则跳转到 method 中的 imp 指向的方法实现。
  5. 若消息转发机制也没能处理,则返回 unreconized selector。

结合 runtime 代码(简化后),理解上述过程。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 消息传递
id _Nullable objc_msgSend(id _Nullable self, SEL _Nonnull op, ...);

// 类
struct objc_class {
Class _Nonnull isa OBJC_ISA_AVAILABILITY;
struct objc_method_list * _Nullable * _Nullable methodLists;
struct objc_cache * _Nonnull cache;
}

// 方法
struct method_t {
SEL name;
const char *types;
IMP imp;
}

// IMP 的声明
id (*IMP)(id, SEL, ...)

可以看出,要想修改方法的实现,只需要修改 imp,因为它指向了方法的实现。

又得益于 Objc 的 Runtime System,在运行期,可以向类中新增或替换特定方法实现。

所以在 Objc 中实现方法交换,并不是一件很难的事。

为什么要在 load 方法里处理?

initialize 和 load 方法,都会自动调用,所以交换方法,可在二者选其一。

官方文档里对 load 的解释:

Invoked whenever a class or category is added to the Objective-C runtime; implement this method to perform class-specific behavior upon loading.

即当类或分类被加载时,load 方法就会被调用。

而对于 Initialize:

Initializes the class before it receives its first message.

即在类被发送第一条消息时,runtime system 会对该类发送一个 initialize() 的消息。

显然,若是在分类中的 load 实现方法交换,有2个好处:

  1. 可以在加载时就处理。
  2. 不用去修改原有代码。

为确保在不同线程中,处理代码只执行一次,需要借助 dispatch_once。

为什么不直接使用 method_exchangeImplementations 即可?

实现例子里,先调用了 class_addMethod,再根据其结果使用 class_replaceMethod 或 method_exchangeImplementations。

为何多此一举,不直接使用 method_exchangeImplementations 呢?

原因是被交换的方法,有可能没在本类中实现,而是在其父类中实现,此时,就需要将其加入到本类中。

所以才有了这样的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 添加 originalSelector 对应的方法
// 注意代码实现的效果是:originalSelector -> swizzledMethod
// 若是方法已经存在,则 didAddMethod 为 NO
BOOL didAddMethod = class_addMethod(class,
originalSelector,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod));

if (didAddMethod) {
// originalMethod 在上面添加成功了
// 下面代码实现: swizzledSelector -> originalMethod
class_replaceMethod(class,
swizzledSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
} else {
// 方法已经存在,直接交换
method_exchangeImplementations(originalMethod, swizzledMethod);
}

思考题

假设有两个分类,都在 load 里,进行了同样的方法交换,那么再调用原来的方法,结果会是如何呢?

以下为简单的代码例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@implementation Cat
- (void)run {
NSLog(@"ori");
}
@end

@impelmentation Cat (A)
// load 里将 run 交换成 a_run

- (void)a_run {
[self a_run];
NSLog(@"A");
}
@end

@impelmentation Cat (B)
// load 里将 run 交换成 a_run

- (void)a_run {
[self a_run];
NSLog(@"B");
}
@end

// 执行以下代码,会得到什么结果呢?
[cat run]; // result: ori

结果也在代码里。

认真想想,很容易理解,处理了两次,又交换回来了。

参考资料

iOS开发·runtime原理与实践: 消息转发篇(Message Forwarding) (消息机制,方法未实现+API不兼容奔溃,模拟多继承) - 掘金
Method Swizzling - NSHipster
load() - NSObject | Apple Developer Documentation
initialize() - NSObject | Apple Developer Documentation

GitHub Pages 搭建博客

发表于 2018-07-01

简介

如果只是搭建简单的个人博客,Github Pages 绝对是值得尝试的方案,它提供了静态网站代码的托管服务。

而 Hexo 或 Jekyll 这类静态博客生成工具,可以生成静态代码。

借助以上工具,作者只需要专注于写作,其他工作由它们完成。

笔者采用了 Hexo,结合 NexT 主题搭建了此博客。

GitHub 配置

新建 repository,名称为 username.github.io,这也是最终的博客网址,其中 username 必须为 GitHub 上的用户名。

如果已有静态网站代码,可以 clone repository 后,将代码复制到相应目录下,再 push 到 GitHub 上。

1
2
# 克隆 repository 来本地
git clone https://github.com/<username>/<username>.github.io

Hexo

安装 Hexo

安装前需要确保已安装 Git 和 Node.js
Mac 自带 Git,直接跳过,笔者使用 Homebrew 安装 Node:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 安装 Node
brew install node
# 安装 hexo
npm install -g hexo-cli
# 成功会有以下提示
/usr/local/bin/hexo -> /usr/local/lib/node_modules/hexo-cli/bin/hexo

> fsevents@1.2.4 install /usr/local/lib/node_modules/hexo-cli/node_modules/fsevents
> node install

[fsevents] Success: "/usr/local/lib/node_modules/hexo-cli/node_modules/fsevents/lib/binding/Release/node-v64-darwin-x64/fse.node" already installed
Pass --update-binary to reinstall or --build-from-source to recompile
+ hexo-cli@1.1.0
added 171 packages from 369 contributors in 29.855s

新建项目

1
2
3
4
# folder 为项目目录名
hexo init <folder>
cd <folder>
npm install

调用 hexo server 或 hexo s --debug(调试模式) 后,可以通过 http://localhost:4000/ 访问本地博客。

NexT 主题

安装前,需要创建 Hexo 项目,然后复制 NexT 到项目目录下:

1
2
cd <hexo site folder>
git clone https://github.com/iissnan/hexo-theme-next themes/next

修改 _config.yml 中的 theme 字段,将其值改为 next。
这样,NexT 主题安装完成。接下来验证主题是否正确启用。
注意:切换主题后,最好使用 hexo clean 来清除缓存。

1
2
3
4
5
hexo clean
# 调试模式启动 Hexo 本地站点,会显示异常信息
hexo s --debug
# 显示以下信息,即为正常
INFO Hexo is running at http://localhost:4000/. Press Ctrl+C to stop.

NexT 相关配置在 themes/next/_config.yml 中。

有多种 Scheme,可根据个人喜欢修改:

1
2
3
4
5
# Schemes
# scheme: Muse
scheme: Mist
#scheme: Pisces
#scheme: Gemini

其他详细设置请参考 开始使用 NexT。

写作

通过 hexo new 来新建一篇文章:

1
2
hexo new [layout] <title> # <title> 不需要后缀名
# 如 hexo new GitHub_Pages_搭建博客

可指定文章的布局(layout),默认为 post,通过修改 _config.yml 中的 default_layout 参数来指定默认布局。

详细参考 Hexo 写作

写完后,生成静态文件

1
hexo generate

部署

生成的静态文件在 public 目录下,可以复制到任何地方。
也可以通过 配置,自动部署到常见平台。

自动部署到 GitHub Pages

安装 hexo-deployer-git

1
npm install hexo-deployer-git --save

修改配置

1
2
3
4
5
deploy:
type: git
repo: <repository url>
branch: [branch]
message: [message]

一键部署

1
hexo deploy

参考资料

Github Pages
开始使用 NexT

Jiandan

2 日志
© 2019 Jiandan
由 Hexo 强力驱动
|
主题 — NexT.Mist v5.1.4