iOS 单例模式

  单例:整个程序中只有一个实例,不论创建多少次,引用的都是同一个内存地址的对象

  以下是其实现方法,只要拷贝就可以直接用了(自己创建一个.h头文件,拷贝进去,调用的话在.h文件使用WYSSingletonH(这里写你的类名),然后在.m文件中调用WYSSingletonM(这里写你得类名),这里包括了ARC和MRC的实现):

// .h文件
#define WYSSingletonH(name)  +(instancetype)shared##name;

// .m文件
#if __has_feature(objc_arc)

    #define WYSSingletonM(name) \
    static id _instace; \
 \
    + (id)allocWithZone:(struct _NSZone *)zone \
    { \
        static dispatch_once_t onceToken; \
        dispatch_once(&onceToken, ^{ \
            _instace = [super allocWithZone:zone]; \
        }); \
        return _instace; \
    } \
 \
    + (instancetype)shared##name \
    { \
        static dispatch_once_t onceToken; \
        dispatch_once(&onceToken, ^{ \
            _instace = [[self alloc] init]; \
        }); \
        return _instace; \
    } \
 \
    - (id)copyWithZone:(NSZone *)zone \
    { \
        return _instace; \
    }

#else

    #define WYSSingletonM(name) \
    static id _instace; \
 \
    + (id)allocWithZone:(struct _NSZone *)zone \
    { \
        static dispatch_once_t onceToken; \
        dispatch_once(&onceToken, ^{ \
            _instace = [super allocWithZone:zone]; \
        }); \
        return _instace; \
    } \
 \
    + (instancetype)shared##name \
    { \
        static dispatch_once_t onceToken; \
        dispatch_once(&onceToken, ^{ \
            _instace = [[self alloc] init]; \
        }); \
        return _instace; \
    } \
 \
    - (id)copyWithZone:(NSZone *)zone \
    { \
        return _instace; \
    } \
 \
    - (oneway void)release { } \
    - (id)retain { return self; } \
    - (NSUInteger)retainCount { return 1;} \
    - (id)autorelease { return self;}

#endif

 

posted @ 2015-04-07 13:53  GeekStar  阅读(124)  评论(0编辑  收藏  举报