iOS开发——单例模式

  一、用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

 

posted on 2016-04-28 09:34  乱七八糟21号  阅读(279)  评论(0)    收藏  举报

导航