iOS开发多线程篇—单例模式
一、简单说明:
设计模式:多年软件开发,总结出来的一套经验、方法和工具
java中有23种设计模式,在ios中最常用的是单例模式和代理模式。
二、单例模式说明
(1)单例模式的作用 :可以保证在程序运行过程,一个类只有一个实例,而且该实例易于供外界访问,从而方便地控制了实例个数,并节约系统资源。
(2)单例模式的使用场合:在整个应用程序中,共享一份资源(这份资源只需要创建初始化1次),应该让这个类创建出来的对象永远只有一个。
例如音频 视频的占用资源大的文件

同时
无论喜欢与否,有时你确实需要使用单例。事实上,每一个 iOS 和 Mac OS 应用都至少用到了一个单例: UIApplication 或 NSApplication 。
具体使用如下
//
// YKPersonGCD(单实例).h
// YKThread(多线程)
//
// Created by Mac on 15/10/8.
// Copyright (c) 2015年 Mac. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface YKPersonGCD_____ : NSObject
+(instancetype)shareInstance;
@end
//
// YKPersonGCD(单实例).m
// YKThread(多线程)
//
// Created by Mac on 15/10/8.
// Copyright (c) 2015年 Mac. All rights reserved.
//
#import "YKPersonGCD(单实例).h"
//定义一个全局的变量(1)
static id shareInstance = nil;
@implementation YKPersonGCD_____
/**
* 为了单实例的程序健壮性 除了静态创建 还要加上alloc 和 copy的调用方法
*/
//创建唯一一个单实例(2)
+(instancetype)shareInstance{
if (!shareInstance) {
shareInstance = [[YKPersonGCD_____ alloc]init];
}
return shareInstance;
}
//核心方法是+(instancetype)allocWithZone:(struct _NSZone *)zone
+(instancetype)alloc{
NSLog(@"alloc");
return [super alloc];
}
//创建内存核心方法(3)
+(instancetype)allocWithZone:(struct _NSZone *)zone {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
shareInstance = [super allocWithZone:zone];
});
return shareInstance;
}
//(4)对象已创建 复制的对象 就是shareInstance
-(id)copy{
return shareInstance;
}
@end
浙公网安备 33010602011771号