美文网首页
iOS 单例模式 - 单例对象销毁【@synchronized】

iOS 单例模式 - 单例对象销毁【@synchronized】

作者: Matt_Z_ | 来源:发表于2021-03-30 12:36 被阅读0次

单例对象的创建方式

单例.h 文件的实现

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface NBUser : NSObject

// 创建单例对象
+ (instancetype)sharedInstance;

// 销毁单例对象
- (void)dellocInstance;

// 用户名
@property (nonatomic, copy) NSString *username;

// 密码
@property (nonatomic, copy) NSString *pwd;

@end

NS_ASSUME_NONNULL_END

单例.m 文件的实现


#import "NBUser.h"

@implementation NBUser
static NBUser *instance = nil;
+ (instancetype)sharedInstance {
    @synchronized(self) {
        if (instance == nil) {
            // 使用super 调用父类等 allocWithZone,避免循环引用
            // 因为重写了 allocWithZone 返回的是 [self sharedInstance],
            // 如果调用了 [self allocWithZone], 就会出现循环调用的问题,
            // 规避循环引用使用 super 进行初始化
            instance = [[super allocWithZone:NULL]init];
        }
    }
    return instance;
}

// 【必不可少】重写 allocWithZone 方法
// 因为不使用 sharedInstance 进行创建对象的情况,也是有可能的
// 比如使用 alloc 进行创建, alloc 会调用 allocWithZone ,
// 重写 allocWithZone,在内部手动调用 [self sharedInstance] 单例创建对象;
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    return  [self sharedInstance];;
}

// 【必不可少】当单例被 copy
// 外界有可能会对当前实例进行copy操作来创建一个对象,
// 要保证一个对象在App生命周期内永远只能被创建一次,
// 我们还需要重写 copyWithZone 方法
// 直接将 self 返回就可以了
- (id)copyWithZone:(NSZone *)zone {
    return self;
}


// 销毁单例对象
- (void)dellocInstance {
    instance = nil;
}
@end

单例对象的销毁【@synchronized创建方式】

使用单例对象的时候,如果我们暂时不用这个对象,同时想释放单例占用的内存空间,所以我们需要把它销毁掉,用的时候在创建出来,那怎么做呢?
上面的代码是包含这部分功能的,操作的方式就是在销毁的方法里面:直接把 instance 置为nil。

  • 下面是销毁的代码
// 销毁单例对象
- (void)dellocInstance {
    instance = nil;
}

相关文章

  • iOS 单例模式 - 单例对象销毁【@synchronized】

    单例对象的创建方式 单例.h 文件的实现 单例.m 文件的实现 单例对象的销毁【@synchronized创建方式...

  • 单例

    iOS单例模式iOS之单例模式初探iOS单例详解

  • iOS 单例模式 - 单例对象销毁【GCD】

    单例对象的创建方式 单例.h 文件的实现 单例的.m 文件的实现 单例对象的销毁【GCD创建的方式】 使用单例对象...

  • 线程同步

    1、synchronized 单例模式下synchronized实现同步 2、lock 单例模式下lock实现同步...

  • iOS 单例模式

    关于单例模式的详解,看完这几篇,就完全了然了。iOS 单例模式iOS中的单例模式iOS单例的写法

  • 创建型 单例模式(上)(单例初入门)(文末有项目连接)

    1:什么是单例设计模式 2:单例模式的应用场景 3:尝试添加 synchronized 对象级别 锁解决 4:尝试...

  • 单利模式

    单例的实现 单例模式的优点: 单例模式在内存中只有一个实例,减少了内存开支。特别是一个对象需要频繁的创建、销毁时,...

  • iOS单例的创建与销毁

    c#iOS单例的创建与销毁 单例:单例模式使一个类只有一个实例.单例是在使用过程,保证全局有唯一的一个实例.这样,...

  • 【浅析iOS中常用设计模式】

    单例模式 单例模式是iOS开发中常用的一种设计模式,目的在于创建一次对象,多地方使用。系统中的单例例如:UIApp...

  • 单例模式 - 饿汉式

    Java 单例模式 单例模式保证了 系统内存中该类只存在一个对象,节省了系统资源,对于一些需要频繁创建销毁的对象,...

网友评论

      本文标题:iOS 单例模式 - 单例对象销毁【@synchronized】

      本文链接:https://www.haomeiwen.com/subject/liowhltx.html