iOS成长日记Part3:Course:51,07.11

单例三个特点

  • 全局只存在一个
  • 再次使用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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值