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

为了方便实用,只要将以下代码定义在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的博客


    原文作者:AirZilong
    原文地址: https://blog.csdn.net/Arodung/article/details/50884273
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞