一次性代码(单例)

 

//  CZTool.h

一次性代码

#import <Foundation/Foundation.h>

 

@interface CZTool : NSObject

 

// 用单例设计模式,可以节省内存.

 

// 书写单例

// 1. 对外提供一个获取单例对象的接口(API)

 

+(instancetype)sharedCZTool;

 

@end

 

 

//  CZTool.m

一次性代码

 

#import "CZTool.h"

 

@implementation CZTool

 

// 定义一个全局的变量来接受创建好的单例对象.

// 目的:为了使其他方法再次创建对象的时候,直接返回这个单例对象

 

static id _instance;

 

+(instancetype)sharedCZTool

{

    // 一次性代码中的代码,只能够被执行一次.

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        

        _instance = [[self alloc] init];

 

    });

    

  //  _instance = [[self alloc] init];

    

    return _instance;

}

 

 

// 当调用 alloc init 方法之后,内部都会调用这个方法.

//+(instancetype)allocWithZone:(struct _NSZone *)zone

//{

//    static dispatch_once_t onceToken;

//    dispatch_once(&onceToken, ^{

//        

//        _instance = [super allocWithZone:zone];

//        

//    });

//    

//    return _instance;

//}

 

@end

 

 

//  ViewController.m

一次性代码

 

#import "ViewController.h"

#import "CZTool.h"

 

@interface ViewController ()

 

@property (nonatomic,assign) BOOL is_onceTime;

 

@end

 

@implementation ViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

    

    self.is_onceTime = YES;

}

 

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

 

    CZTool *tool1 = [CZTool sharedCZTool];

    CZTool *tool2 = [CZTool sharedCZTool];

    CZTool *tool3 = [CZTool sharedCZTool];

    CZTool *tool4 = [CZTool sharedCZTool];

    

    CZTool *tool = [[CZTool alloc] init];

 

    NSLog(@"%@,%@,%@,%@,%@",tool1,tool2,tool3,tool4,tool);

    

    

}

 

 

- (void)onceTime

{

    // 实际开发中,GCD提供了一次性代码的函数.是线程安全的一次性代码.

    

    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        

        [self test2];

    });

    

    [self performSelectorInBackground:@selector(test2) withObject:nil];

    

    

    [NSThread detachNewThreadSelector:@selector(test2) toTarget:self withObject:nil];

    

    [self test2];

}

 

// GCD中的一次性代码,需要掌握.

// 在写单例的时候,经常使用.

// 最简单的实现单例设计模式的方法.

- (void)test2

{

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        

        NSLog(@"一次性代码,只执行一次");

 

    });

}

 

- (void)isOnceTime

{

    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        

        [self test];

    });

    

    [self performSelectorInBackground:@selector(test) withObject:nil];

    

    

    [NSThread detachNewThreadSelector:@selector(test) toTarget:self withObject:nil];

    

    [self test];

}

 

 

// 如果使用Bool值做判断,为了保证线程安全,必须加锁.

- (void)test

{

    @synchronized(self)

    {

        if (self.is_onceTime) {

        

        NSLog(@"一次性代码,只执行一次");

        self.is_onceTime = NO;

    }

        

}

    

 

    

}

 

@end

posted @ 2015-09-03 17:56  记忆里的那座沙城  阅读(672)  评论(0编辑  收藏  举报