10.4 static单例类

创建一个Animal类

Paste_Image.png
#import 

@interface Animal : NSObject
//单例类
+ (instancetype)shareAnimal;
@end
Paste_Image.png
#import "Animal.h"

@implementation Animal
//实现单例类,非常重要,一定要会直接手写
+ (instancetype)shareAnimal{

    static Animal *animal = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{ 
        animal = [[Animal alloc]init];
    });    
    return animal;
}

- (void)dealloc{

    NSLog(@"animal dealloc");
}
@end
Paste_Image.png
#import "ViewController.h"
#import "Animal.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//调用单例类,这两个aniaml 指向的是同一个对象,而且没有执行Animal类里面的deallog销毁方法
    Animal *aniaml = [Animal shareAnimal];
    Animal *aniaml2 = [Animal shareAnimal];

}

@end

你可能感兴趣的:(10.4 static单例类)