单例的使用

来源:互联网 发布:怎么把域名和ip绑定 编辑:程序博客网 时间:2024/05/16 03:57

如何创建 和运用单例

第一步专门一个单例的.h文件 

再继续用自己所需要的单例,创建.h 和.m 文件 








  如何运用:


单例代码如下

// .h

#define singleton_interface(class) + (instancetype)shared##class;


// .m

#define singleton_implementation(class) \

static class *_instance; \

\

+ (id)allocWithZone:(struct _NSZone *)zone \

{ \

    static dispatch_once_t onceToken; \

    dispatch_once(&onceToken, ^{ \

        _instance = [super allocWithZone:zone]; \

    }); \

\

    return _instance; \

} \

\

+ (instancetype)shared##class \

{ \

    if (_instance == nil) { \

        _instance = [[class alloc] init]; \

    } \

\

    return _instance; \

}

    以上是老师的定义的类,拿来运用。

0 0
原创粉丝点击