iOS单例模式的写法

iOS单例模式的写法

1、第一种

static AccountManager *DefaultManager = nil;

+ (AccountManager *)sharedManager {
    if (!DefaultManager) {
        DefaultManager = [[self allocWithZone:NULL] init];
        return DefaultManager;
    }
 }

这种写法很普通,就是设置一个对象类型的静态变量,判断这个变量是否为nil,来创建相应的对象

2.第二种

iOS4.0之后,官方推荐了另一种写法:

+(AccountManager *)sharedManager{
    static AccountManager *defaultManager = nil;
    disptch_once_t once;
    disptch_once(&once,^{
        defaultManager = [[self alloc] init];
        }
    )
    return defaultManager;
}

第二种写法有几点好处:
1.线程安全
2.满足静态分析器的要求
3.兼容了ARC

根据苹果文档的介绍

dispatch_once

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

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.

Discussion

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 is undefined.

Availability

Available in iOS 4.0 and later.

Declared In

dispatch/once.h

#######从文档中我们可以看到,该方法的主要作用就是在程序运行期间,仅执行一次block对象。所以说很适合用来生成单例对象,其实任何只需要执行一次的代码我们都可以使用这个函数。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容