首页 > 解决方案 > 是否有任何原因无法初始化静态变量?

问题描述

我有一个具有三个全局静态变量的类(单例类)。这些静态变量中的每一个都具有相同的类型(另一个具有自定义 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”值。

谁能帮我解决这个问题?

标签: iosobjective-cstatic

解决方案


推荐阅读