一、用if语句实现单例
1.在.h文件中
#import <Foundation/Foundation.h>
@interface YYTRequestTool : NSObject
+(id)sharedYYTRequestTool;
@end
2.在.m文件中
#import "YYTRequestTool.h"
@interface YYTRequestTool ()
@property(nonatomic,strong) DPAPI *api;
@end
@implementation YYTRequestTool
static YYTRequestTool *sharedYYTRequestTool = nil;
+(id)sharedYYTRequestTool{
if (!sharedYYTRequestTool) {
sharedYYTRequestTool = [[self alloc] init];
}
return sharedYYTRequestTool;
}
@end
二、用dispatch_once_t实现单例
1.在.h文件中
#import <Foundation/Foundation.h>
@interface YYTRequestTool : NSObject
+(id)sharedYYTRequestTool;
@end
2.在.m文件中
#import "YYTRequestTool.h"
@interface YYTRequestTool ()
@property(nonatomic,strong) DPAPI *api;
@end
@implementation YYTRequestTool
+(id)sharedYYTRequestTool{
static YYTRequestTool *sharedYYTRequestTool = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedYYTRequestTool = [[self alloc] init];
});
return sharedYYTRequestTool;
}
@end