这篇文章主要给大家介绍了关于swift中如何正确安全声明一个单例的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
Talk is cheap. Show me the code.
class TestShareInstance{
var age:Int
static let shareInstane:TestShareInstance = TestShareInstance(age: 3);
private init(age:Int){
self.age = age;
};
}
说说原理
swift在类中,类变量是能够保证线程安全,swift底层,static关键字的实际上是使用dispatch_once语法来实现的,如下一段swift编译中间产物SIL语言中的代码就能看到底层的实现.
1.staic变量被声明为全局变量
// static TestShareInstance.shareInstane
sil_global hidden [let] @static main.TestShareInstance.shareInstane : main.TestShareInstance : $TestShareInstance
2.在get方法中获取变量调用了swift内嵌的builtin "once",实际上调用的是swift_once方法
3.在swift源码中可以搜索到swift_once方法的内部实现如下,内部调用的就是GCD底层的dispatch_once_f,保证了单例的线程安全。
/// Runs the given function with the given context argument exactly once.
/// The predicate argument must point to a global or static variable of static
/// extent of type swift_once_t.
void swift::swift_once(swift_once_t *predicate, void (*fn)(void *),
void *context) {
#if defined(__APPLE__)
dispatch_once_f(predicate, context, fn);
#elif defined(__CYGWIN__)
_swift_once_f(predicate, context, fn);
#else
std::call_once(*predicate, [fn, context]() { fn(context); });
#endif
}
在类中,将TestShareInstance的init方法设置为了private,这能保证其他人没有办法调用你的init的方法,只能调用你的shareInstane单例变量;从而保证了单例的不可修改特性。如果你要强行修改,编译器就会警告你,具体示例如下
到此这篇关于swift中正确安全声明一个单例的文章就介绍到这了,更多相关swift正确安全声明单例内容请搜索编程学习网以前的文章希望大家以后多多支持编程学习网!
本文标题为:swift中正确安全声明一个单例的方法实例
- R语言-如何切换科学计数法和更换小数点位数 2022-11-23
- Ruby的字符串与数组求最大值的相关问题讨论 2023-07-22
- Go Web开发进阶实战(gin框架) 2023-09-06
- R语言关于二项分布知识点总结 2022-11-30
- Ruby on Rails在Ping ++ 平台实现支付 2023-07-22
- Ruby 迭代器知识汇总 2023-07-23
- R语言绘图数据可视化pie chart饼图 2022-12-10
- Golang http.Client设置超时 2023-09-05
- Swift超详细讲解指针 2023-07-08
- 汇编语言程序设计之根据输入改变屏幕颜色的代码 2023-07-06
