单例的使用

如何创建 和运用单例

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

单例的使用_第1张图片

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

单例的使用_第2张图片




单例的使用_第3张图片




  如何运用:


单例代码如下

// .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; \

}

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

你可能感兴趣的:(iOS)