实现步骤
- 定义一个静态变量来存储单例实例。
- 使用
dispatch_once
函数来确保单例实例只被创建一次。
代码实现
#import <Foundation/Foundation.h>
@interface Singleton : NSObject
@property (nonatomic, strong, readonly) NSString *name;
+ (instancetype)sharedInstance;
@end
@implementation Singleton
static Singleton *sharedInstance = nil;
+ (instancetype)sharedInstance {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] init];
sharedInstance.name = @"Singleton Name";
});
return sharedInstance;
}
@end
好处
- 线程安全:
dispatch_once
函数是线程安全的,无论在多少个线程中调用sharedInstance
方法,单例实例只会被创建一次,无需额外的锁机制来保证线程安全。
- 延迟加载:单例实例在第一次调用
sharedInstance
方法时才会被创建,提高了程序的启动性能,避免了不必要的资源消耗。