测试已测试 | ✓ |
Lang语言 | Obj-CObjective C |
许可证 | MIT |
发布最后发布 | 2016年1月 |
由 Jiakai Lian 维护。
如 Apple 所述,NSDictionary、NSArray 和 NSSet 是线程安全的,但并非所有相应的可变类。JKLThreadSafeMutableCollection 通过一个轻量级解决方案来开发,以替换所有这些可变类。这个集合包括 JKLThreadSafeMutableDictionary、JKLThreadSafeMutableArray 和 JKLThreadSafeMutableSet。所有这些类都支持大多数原始 NSMutable 方法,包括索引功能(例如,字典[key],数组[index])。
在线程安全实现方面,这个集合中的所有类都在一个并发 GCD 队列上应用了 并发读和独占写 模型。有关不同线程安全实现之间的性能比较,请检查另一个仓库 ThreadSafeClassDesign。
这些类利用 Objective-C 运行时简化方法调用过程。而不是为线程安全重写每个方法,实现了一个自定义消息传递机制来通过返回类型将外部方法调用传递给内部对象。因此,大多数对象方法不需要重写,除了类方法、初始化方法和一些特殊方法。
以下私有方法是上述解释的核心方法。
- (void)forwardInvocation:(NSInvocation *)origInvocation {
if ([self.internalObject respondsToSelector:[origInvocation selector]]) {
__weak typeof(self) weakSelf = self;
NSMethodSignature *methodSignature = [origInvocation methodSignature];
const char *type = [methodSignature methodReturnType];
if (*type == *@encode(void)) {
// write operations
dispatch_barrier_async(self.queue, ^{
__strong typeof(self) strongSelf = weakSelf;
[origInvocation invokeWithTarget:strongSelf.internalObject];
});
} else {
// read operations
dispatch_sync(self.queue, ^{
__strong typeof(self) strongSelf = weakSelf;
[origInvocation invokeWithTarget:strongSelf.internalObject];
});
}
}
}
要运行示例项目,克隆仓库,然后首先从 Example 目录运行 pod install
。
JKLThreadSafeMutableCollection 通过 CocoaPods 提供。要安装它,请简单地添加以下行到您的 Podfile 中
pod "JKLThreadSafeMutableCollection", '~> 0.1.0'
jiakai lian, [email protected]
JKLThreadSafeMutableCollection 在 MIT 许可证下可用。有关更多信息,请参阅 LICENSE 文件。