单例三个特点
- 全局只存在一个
- 再次使用alloc方法会崩溃并退出
- 随着程序的开始被创建
Demo
@interface newAVPlayer : AVPlayer
+ (instancetype)sharedMusicPlayer;//.h文件中的继承关系和取出播放器的方法声明
@end
以一个音乐播放器为例子设计一个单例
- 首先创建一个类名为“newAVPlayer”
- 全局只能存在一个
static newAVPlayer* _instancetype;
- 随着程序的开始被创建
+ (void)load{
_instancetype =[[newAVPlayer alloc]init];
}
- 其他代码工作者第二次使用alloc或者在已有播放器时使用alloc会崩溃并给出报错信息
- 实现方法:通过重新父类的alloc方法
+ (instancetype)alloc{
if(!_instancetype){
return [super alloc];
}else{
NSException*exc = [NSException exceptionWithName:@"name" reason:@"reason" userInfo:nil];
[exc raise];
return 0;
}
}
- .m文件中取播放器方法的实现
+ (instancetype)sharedMusicPlayer{
return _instancetype;
}
整个.m文件
//
// singlePlayer.m
// singleTest
//
// Created by 千千 on 2019/7/11.
// Copyright © 2019 千千. All rights reserved.
//
#import <AVFoundation/AVFoundation.h>
#import "newAVPlayer.h"
static newAVPlayer* _instancetype;
@implementation newAVPlayer
+ (void)load{
_instancetype =[[newAVPlayer alloc]init];
}
+ (instancetype)sharedMusicPlayer{
return _instancetype;
}
+ (instancetype)alloc{
if(!_instancetype){
return [super alloc];
}else{
NSException*exc = [NSException exceptionWithName:@"name" reason:@"reason" userInfo:nil];
[exc raise];
return 0;
}
}
@end
tips
- 一般在.m文件中将为一的对象名称声明为_instancetype