新建Singleton.h的頭文件
內(nèi)容如下:
// @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; \
}
使用方法
先導(dǎo)入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相關(guān)的功能
*/
@interface OpenHABWiFi : NSObject
// 單例模式
singleton_interface(OpenHABWiFi)
/**
開(kāi)始監(jiān)聽(tīng)WiFi的變化
*/
- (void)starListeningWiFiChange;
/**
停止監(jiān)聽(tīng)WiFi的變化
*/
- (void)stopListeningWiFiChange;
@end
實(shí)現(xiàn)文件
//
// 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)
// 單例模式模式初始化內(nèi)容
-(instancetype)init
{
if (self = [super init]) {
}
return self;
}
- (void)starListeningWiFiChange{
}
- (void)stopListeningWiFiChange{
}
@end
在其他類中的使用
先導(dǎo)入頭文件砖顷,再按照如下方法使用
[[OpenHABWiFi sharedOpenHABWiFi] startSSDP];