新建Singleton.h的头文件
内容如下:
// @interface
#define singleton_interface(className) \
+ (className *)shared##className;
// @implementation
#define singleton_implementation(className) \
static className *_instance; \
+ (id)allocWithZone:(NSZone *)zone \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [super allocWithZone:zone]; \
}); \
return _instance; \
} \
+ (className *)shared##className \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [[self alloc] init]; \
}); \
return _instance; \
}
使用方法
先导入Singleton.h的头文件
//
// OpenHABWiFi.h
// openHAB
//
// Created by XMYY-19 on 2018/1/18.
// Copyright © 2018年 openHAB e.V. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Singleton.h"
/**
WiFi相关的功能
*/
@interface OpenHABWiFi : NSObject
// 单例模式
singleton_interface(OpenHABWiFi)
/**
开始监听WiFi的变化
*/
- (void)starListeningWiFiChange;
/**
停止监听WiFi的变化
*/
- (void)stopListeningWiFiChange;
@end
实现文件
//
// OpenHABWiFi.m
// openHAB
//
// Created by XMYY-19 on 2018/1/18.
// Copyright © 2018年 openHAB e.V. All rights reserved.
//
#import "OpenHABWiFi.h"
@implementation OpenHABWiFi
singleton_implementation(OpenHABWiFi)
// 单例模式模式初始化内容
-(instancetype)init
{
if (self = [super init]) {
}
return self;
}
- (void)starListeningWiFiChange{
}
- (void)stopListeningWiFiChange{
}
@end
在其他类中的使用
先导入头文件,再按照如下方法使用
[[OpenHABWiFi sharedOpenHABWiFi] startSSDP];