Algorithm

LeetCode 225:用队列实现栈

使用队列实现栈的下列操作:
push(x) – 元素 x 入栈
pop() – 移除栈顶元素
top() – 获取栈顶元素
empty() – 返回栈是否为空

思路

本题主要考察这个数据结构的特性,比较简单。

解答

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
class MyStack {
var queue: [Int]

init() {
queue = [Int]()
}

func push(_ x: Int) {
queue.append(x)
}

func pop() -> Int {
guard !queue.isEmpty else { return 0 }
return queue.popLast() ?? 0
}

func top() -> Int {
guard !queue.isEmpty else { return 0 }
return queue.last ?? 0
}

func empty() -> Bool {
return queue.isEmpty
}
}

Review

Binding to a table view with multiple cells and sections

本篇文章介绍了两种使用RxSwifttableView与多种类型的 cell 和 section 绑定的方式。一种是用RxCocoabind(to:),好处是不需添加额外依赖且逻辑简单,但无法绑定 section,另一种是使用RxDataSources,可适用多重 cell 和 section 的场景,也是笔者比较推荐的方式。

本文以简单例子介绍了如何将数据流绑定到tableView上,算是一篇比较好的上手材料。

Tip

记录一个手势处理的问题,场景是一个自定义弹层添加了UISwipeGestureRecognizer的手势,目的是在用户左滑 pop 的时候可以拦截该手势并将弹层 dismiss,否则会出现 controller 被 pop 后弹层仍在显示的问题。

但实际发现并不能有效拦截该手势,猜测是系统的 gesture distance 更小,故处理方式为添加一个代理方法以达到手势并行处理的效果:
gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool

这样自行注册的UISwipeGestureRecognizer便可同时相应事件了。

同时,当遇到手势冲突需要取舍时,可以试试以下两个代理方法:

1
2
3
4
5
// 返回 true 时,gestureRecognizer 会失效
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer) -> Bool

// 返回 true 时,otherGestureRecognizer 会失效
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool

Share

iOS微信内存监控

本篇文章出自微信测试团队,背景是当时微信的日志无法正确反映 FOOM (Foreground Out Of Memory)的具体原因,从而开发的一款内存监控工具,介绍了实现原理、误判降低以及最后成果。

过程中有许多亮点值得学习,比如对 libmalloc 接口的使用、为了降低数据大小而对数据结构的选择以及如何减少误判的思路等等。

目前公司也准备开发一个数据上报组件,因此分享这篇文章。