Create singleton using GCD's dispatch_once in Objective-C

后端 未结 10 2465
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 07:26

If you can target iOS 4.0 or above

Using GCD, is it the best way to create singleton in Objective-C (thread safe)?

+ (instancetype)sharedInstance
{
          


        
10条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 07:46

    This is a perfectly acceptable and thread-safe way to create an instance of your class. It may not technically be a "singleton" (in that there can only ever be 1 of these objects), but as long as you only use the [Foo sharedFoo] method to access the object, this is good enough.

提交回复
热议问题