为什么常量属性可能会在 Swift 类中初始化两次?

P. *_*sin 3 xcode objective-c ios swift

我正在从事的项目是 Swift 和 Objective-C 的混合体。这是片段:

// ViewController.m
@interface ViewController ()

@property (nonatomic, strong) MyModel *model;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.model = [[MyModel alloc] initWithIntValue:10];
}

// MyModel.swift
fileprivate class SomeProperty {
    init() {
        print("SomeProperty init")
    }
}

class MyModel: BaseModel {
    private let property = SomeProperty()
}

// BaseModel.h
@interface BaseModel : NSObject

- (instancetype)initWithIntValue:(int)intValue;
- (instancetype)initWithIntValue:(int)intValue doubleValue:(double)doubleValue;

@end

// BaseModel.m
@implementation BaseModel

- (instancetype)initWithIntValue:(int)intValue doubleValue:(double)doubleValue {
    if (self = [super init]) {
        
    }
    return self;
}

- (instancetype)initWithIntValue:(int)intValue {
    return [self initWithIntValue:intValue doubleValue:0];
}

@end
Run Code Online (Sandbox Code Playgroud)

有趣的是,我发现当MyModel实例初始化时,SomeProperty init会被打印两次,这意味着创建了两个SomeProperty实例。更糟糕的是,调试内存图显示存在SomeProperty对象内存泄漏。那么这是为什么?我该如何解决它?

mat*_*att 6

像这样重写BaseModel.h :

\n
- (instancetype)initWithIntValue:(int)intValue;\n- (instancetype)initWithIntValue:(int)intValue doubleValue:(double)doubleValue NS_DESIGNATED_INITIALIZER;\n
Run Code Online (Sandbox Code Playgroud)\n

请注意NS_DESIGNATED_INITIALIZER第二个初始值设定项末尾的标记。(您可能需要滚动我的代码才能看到它。)

\n

除了它在 Objective-C 中的作用(作为宏)之外,这个标记还告诉 Swift 这两个初始化器都不是指定的初始化器;相反,Swift 总结道,第一个是一个方便的初始化器。这是正确的;它调用另一个初始化程序,即 \xe2\x80\x94 在这种情况下 \xe2\x80\x94 指定的初始化程序。

\n

如果没有这个NS_DESIGNATED_INITIALIZER标记,Swift 就会错误地解释这种情况,因为 Swift 初始化器和 Objective-C 初始化器之间的关系(已经相当复杂)。它认为两个初始化器都是指定初始化器,并且您从 Swift 获得了这个奇怪的双重初始化。

\n