iOS宏定义方法来初始化一个单例对象

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Arodung/article/details/50884273


为了方便实用,只要将以下代码定义在header文件或者.pch文件即可;


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

}


使用方法:

Manager.h文件

#import <Foundation/Foundation.h>


@interface Manager :NSObject


singleton_interface(Manager);


@end


Manager.m文件

#import "Manager.h"


@interface Manager ()


@end


@implementation Manager


singleton_implementation(Manager)


@end


viewController调用

Manager *manager = [ManagersharedManager];


如果转载请注明转于:AirZilong的博客




展开阅读全文

没有更多推荐了,返回首页