ios - 没看懂swift编程中initialize的过程

标签 ios swift architecture ios8 initialization

我正在学习 Swfit,我从下面的链接开始学习
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html

我对 swift 中的Initialization 有疑问。

我的理解如下

1] 它的工作方式类似于 swift 类的构造函数。
2] 我们必须初始化其中的所有属性。
3] 我们必须调用父类(super class)的 init() 方法。
4] 在调用 init() 之前,我们必须初始化每个属性。
5] 我们可以在初始化后使用父类(super class)的任何成员或方法。

在以上5点的基础上,我创建了一个类。
但由于第 3、4 和 5 点而出现问题。

/*
AdminManagmentSystem
- Some class which will consume lots of memory during init
*/
class AdminManagmentSystem {

    var adminKey : String
    init(key:String)
    {
        self.adminKey = key;
        println("Consume lots of memory");
    }
}

/*
Person
- A base class which can create key.
*/
class Person {

    // Some property which will user to create private key.
    private var privateKey : String = "private"
    init()
    {
        privateKey = "private";
    }

    // function which will calculate key (Comman for all person type)
    private  func calculatekey() -> NSString
    {
        return self.privateKey + " key";
    }
}

/*
Admin
- A sub class which have object of AdminManagmentSystem
*/
class Admin : Person {

    // Constant variable
    let adminmanagmennt : AdminManagmentSystem

    override init()
    {
        self.adminmanagmennt = AdminManagmentSystem(key: ""); // Line1 : Consume lots of memory
        super.init(); // Line2 : its compalsurry to call super.init
        var adminKey = super.calculatekey(); // Line3 : We can use any member or method of supper after callign init().
        self.adminmanagmennt = AdminManagmentSystem(key: adminKey); // Line4 : Again consume lots of memory
    }
}


下载项目
https://www.dropbox.com/s/afohuxpxxkl5b3c/understandInheritance.zip?dl=0


问题
Line1Line4 中,我必须创建消耗大量内存的 AdminManagmentSystem 对象。

问题
1] 为什么 swift 强制在调用 super.init() 之前初始化每个属性?
2] 如果我让我的属性保持常量,为什么 swift 允许我在 init 方法中多次初始化它?
3] 为什么我必须在 init() 之前写 override 关键字?

最佳答案

回答 1 -

来自 Swift 编程语言 -

“As mentioned above, the memory for an object is only considered fully initialized once the initial state of all of its stored properties is known. In order for this rule to be satisfied, a designated initializer must make sure that all its own properties are initialized before it hands off up the chain.”

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/au/jEUH0.l

因此,在对象完全初始化之前,对象处于未定义状态,这可能是“不安全的”,因此 Swift 要求在阶段 1 中初始化所有属性。

回答 2

初始化函数是一种特殊情况 - 它的工作是将对象设置为初始状态,因此您可以修改“常量”属性,因为对象仍在创建过程中 -

“You can modify the value of a constant property at any point during initialization, as long as it is set to a definite value by the time initialization finishes.”

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/au/jEUH0.l

在对 3 的回答中,因为您正在覆盖一个与父类(super class)具有相同签名的方法(无参数 init 函数)。 override 关键字向编译器表明您知道自己在做什么。如果编译器默默地让您重新声明一个父类(super class)方法,您可能没有意识到您正在这样做并得到意想不到的结果。

在回答有关内存消耗的问题时,ARC 将快速回收为对象的第一个实例分配的内存。如果这是一个性能问题,那么重构 AdminManagmentSystem 类就相当简单了,这样就有一个函数可以重置现有实例上的 key -

class Admin : Person {

    // Constant variable
    let adminmanagmennt : AdminManagmentSystem

    override init()
    {
        self.adminmanagmennt = AdminManagmentSystem(key: ""); // Line1 : Consume lots of memory
        super.init(); // Line2 : its compalsurry to call super.init
        var adminKey = super.calculatekey(); // Line3 : We can use any member or method of supper after callign init().
        self.adminmanagmennt.key=adminKey;  // You can use a property observer function if a simple assignment isn't enough
    }
}

关于ios - 没看懂swift编程中initialize的过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27398668/

相关文章:

ios - 在iOS中查看Custom Directory的内容

ios - 从 JSON 解析时的多个 UITableViewCell 类型

ios - 圆形 UIView 上的 CGAffineTransformMakeScale 动画为正方形

ios - 如何测试 RxSwift Observable.interval 进度

java - 架构事件驱动的建议

ios - UISplitView 中的委托(delegate)未被调用

ios - 如何在 iOS 中获得一个不会过期的缓存?

python - 命令 PhaseScriptExecution 失败,退出代码非零,Xcode 10.1 dyld : Library not loaded:/usr/local/opt/readline/lib/libreadline. 7.dylib

sql-server - 缓存到 Web 服务器上的本地 SQL 实例

c# - 哪种设计模式允许获得此架构