單例的使用

如何創建 和運用單例

第一步專門一個單例的.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; \

}

    以上是老師的定義的類,拿來運用。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章