ios - 是否有任何原因无法初始化静态变量?
问题描述
我有一个具有三个全局静态变量的类(单例类)。这些静态变量中的每一个都具有相同的类型(另一个具有自定义 init 方法的类)。
当我想初始化静态变量时,即使自定义 init 方法返回一个有效实例,其中一个变量的值也为“nil”。
请考虑上面的代码。
//The header file of the singleton class
#import "B.h"
static B *firstVariable;
static B *secondVariable;
static B *thirdVariable;
@interface A : NSObject
//some properties and methods declarations here
@end
//The implementation file of the singleton class
#import "A.h"
@implementation A
static A *sharedInstance = nil;
+ (A *)sharedInstance {
if (sharedInstance == nil) {
sharedInstance = [[A alloc] init];
}
return sharedInstance;
}
...
@end
//The header file for the other class
@interface B : NSObject
@property(nonatomic, strong, readonly) NSString *path;
- (instancetype)initWithPath:(NSString *)path;
@end
//The implementation of this class
#import "B.h"
@implementation B
- (instancetype)initWithPath:(NSString *)path {
self = [super init];
if (self) {
_path = path;
}
return self;
}
@end
这就是我尝试初始化那些静态变量的方式
firstVariable = [[B alloc] initWithPath:@"firstPath"];
secondVariable = [[B alloc] initWithPath:@"secondPath"];
thirdVariable = [[B alloc] initWithPath:@"thirdPath"];
正如我之前提到的,即使在返回之前“initWithPath”方法内部存在有效实例,“secondVariable”也具有“nil”值。
谁能帮我解决这个问题?
解决方案
推荐阅读
- google-cloud-platform - 谷歌云免费信用差异
- react-native - FlatList 和 VirtualizedList 的区别
- javascript - 如何监控 Firebase 数据库中特定字段的更改?
- javascript - Javascript 文件中的共享变量返回旧值
- asp.net-core - 将 .NET Core 重新定位到 net471、net 472
- c# - Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ForEachAsync 的意外行为
() - node.js - 仅访问当前用户数据
- c++ - 动态找出Lua function()的返回值个数?
- python-2.7 - 为什么在 sort() 方法中 deos 两个参数函数在没有参数的情况下运行,为什么该函数应该有两个参数?
- mongodb - mongo db 没有在 ubuntu 上启动