技术点滴

每期一题,打实基础

iOS

Runtime 源码下载地址

weak实现原理?

当我们需要打破循环引用的时候就需要使用weak对象.经常使用在块中对self的使用,例如: __weak wSelf = self, 那么为什么使用了weak对象就能实现打破循环应用呢? weak内部是如何实现的呢? 下面我们找到源码看一下objc-weak.h, 其实头文件注释写的很清楚了.

The weak table is a hash table governed by a single spin lock. An allocated blob of memory, most often an object, but under GC any such allocation, may have its address stored in a __weak marked storage location through use of compiler generated write-barriers or hand coded uses of the register weak primitive. Associated with the registration can be a callback block for the case when one of the allocated chunks of memory is reclaimed. The table is hashed on the address of the allocated memory. When __weak marked memory changes its reference, we count on the fact that we can still see its previous reference.

So, in the hash table, indexed by the weakly referenced item, is a list of all locations where this address is currently being stored.

For ARR, we also keep track of whether an arbitrary object is being deallocated by briefly placing it in the table just prior to invoking dealloc, and removing it via objc_clear_deallocating just prior to memory reclamation.

关键字: spin lock,

算法

2016-08-24

http 协议缓存 和 iOS 缓存有什么关系吗?