GithubHelp home page GithubHelp logo

bhsingleton's Introduction

iOS单例的创建和销毁

GitHub Demo: https://github.com/BaHui/BHSingleton

简介

单例: 单独的实例. 单例模式是一种常用的 设计模式.

创建和销毁:

#import <Foundation/Foundation.h>

@interface BHSingletonObject : NSObject

// 创建单例
+ (instancetype)sharedInstance;

// 销毁单例 
+ (void)deallocInstance;

@end
#import "BHSingletonObject.h"

@implementation BHSingletonObject

static dispatch_once_t onceToken = 0;
static BHSingletonObject *singletonObject = nil;

+ (instancetype)sharedInstance {
/*dispatch_once主要是根据onceToken的值来决定怎么去执行代码。
当onceToken = 0 时,线程执行block中代码 (表示: 从未执行过)
当onceToken = -1 时,线程跳过block中代码不执行 (表示: 已经执行过一次)
当onceToken = 其他值 时,线程被线程被阻塞,等待onceToken值改变 (多线程中可见)
*/
dispatch_once(&onceToken, ^{
singletonObject = [[BHSingletonObject alloc] init];
});

return singletonObject;
}

+ (void)deallocInstance {
onceToken = 0;
singletonObject = nil;
}

@end

交流与建议

bhsingleton's People

Contributors

bahui avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.