• 关于单例设计模式


    在ios开发中,很多时候我们会需要用到单例,一般我们会用到两种实现单例的方式。第一种是:

    第二种是:

    针对这两个方法,我们提出两点疑问:

    1.为什么必须用static修饰符?

    2.这两种方法有什么区别?

    我们先来回答第一个问题。static修饰符在这里的作用就是把变量分配在静态存储区,并且只会分配一次内存,无论你调用多少次这个方法,被static修饰的变量就是它第一次分配的那个,它的生命周期是从应用程序开始到应用程序结束。这样就保证了这个单例对象的唯一性。如果我们不用static修饰符,那么每次调用这个单例方法的时候,系统每次都会在栈上分配一个变量,这样生成的实例就不唯一了。

    这两种生成单例的方法的区别是方法一不是线程安全的,在多线程的环境下可能有多个线程同时调用了方法一,造成生成不同的实例,而方法二是线程安全的,这附上苹果官方文档的解释:

    dispatch_once


    Executes a block object once and only once for the lifetime of an application.

    Declaration


    void dispatch_once( dispatch_once_t *predicate, dispatch_block_t block);


    Parameters

    predicate:A pointer to a dispatch_once_t structure that is used to test whether the block has completed or not.


    block:The block object to execute once.

    This function is useful for initialization of global data (singletons) in an application. Always call this function before using or testing any variables that are initialized by the block.If called simultaneously from multiple threads, this function waits synchronously until the block has completed.The predicate must point to a variable stored in global or static scope. The result of using a predicate with automatic or dynamic storage (including Objective-C instance variables) is undefined.

  • 相关阅读:
    e870. 获取默认外观的数据
    e867. 获取和设置外观
    e776. 设置JList组件项的提示语
    e775. 设置JList组件项的维数
    e781. 设置JList中的选择模式
    e784. 监听对JList选择变动
    e780. 设置JList中的已选项
    e782. 排列JList中的项
    e779. 获得JList中的已选项
    e777. 获得JList组件的所有项
  • 原文地址:https://www.cnblogs.com/qmmq/p/5279567.html
Copyright © 2020-2023  润新知