objective-c - oc单例的一些问题

浏览:60日期:2023-12-09

问题描述

第一种不能在全局使用...没有值。第二种可以..搞不清楚原理阿

1.+ (User *)shareUser {

static User *_sharedSingleton = nil;static dispatch_once_t predicate;dispatch_once(&predicate, ^{ _sharedSingleton = [[self alloc] init];});return _sharedSingleton;

}

2.static User *_sharedSingleton = nil;

@implementation User

(User *)shareUser { static dispatch_once_t predicate; dispatch_once(&predicate, ^{

_sharedSingleton = [[self alloc] init];

}); return _sharedSingleton;}

(id)allocWithZone:(NSZone *)zone{ if (_sharedSingleton == nil) {

_sharedSingleton = [super allocWithZone:zone];

} return _sharedSingleton;}

(id)copyWithZone:(NSZone *)zone{ return _sharedSingleton;}

问题解答

回答1:

是这样的,第一种是现在ObjC单例的标准代码。

+ (User *)shareUser {static User *_sharedSingleton = nil; //静态全局变量static dispatch_once_t predicate;dispatch_once(&predicate, ^{ _sharedSingleton = [[self alloc] init]; //dispatch once 保证大括号里的代码只执行一次});return _sharedSingleton;}

这种方式的单例,是ARC(自动内存管理)模式下的标准形式,外部调用时,直接[类名 shareUser]获取单例,记得h文件中要写接口,不要使用_sharedSingleton。

xxx.h

@interface xxx : xxx{}+ (instancetype)shareUser;@end

这里的instancetype返回当前类的类型。

至于第二段代码把static User *_sharedSingleton = nil;写成全局变量,是MRC时代的写法,包括重写(id)allocWithZone:(NSZone *)zone等方法,也是旧式写法。

回答2:

static关键字修饰的静态变量的生命周期都是一样的,编译时初始化,只有当程序退出后内存才会释放!然而,变量是存在作用域的,就比如你的第一种写法,这个变量是一个局部静态变量,只能在该方法中使用!而你的第二种写法,这个变量是一个全局静态变量,可以全局使用

相关文章: