10.4 static单例类

2016-10-04  本文已影响10人  jayck

创建一个Animal类

Paste_Image.png
#import <Foundation/Foundation.h>

@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
上一篇下一篇

猜你喜欢

热点阅读