Link to yourself in super.init

I have the following code ( EDIT: Updated code so everyone can compile and see it ):

import UIKit

struct Action
{
    let text: String
    let handler: (() -> Void)?
}

class AlertView : UIView
{
    init(actions: [Action]) {
        super.init(frame: .zero)

        for action in actions {
//            let actionButton = ActionButton(type: .custom)
//            actionButton.title = action.title
//            actionButton.handler = action.handler
//            addSubview(actionButton)
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class TextAlertView : AlertView
{
    init() {
        super.init(actions: [
            Action(text: "No", handler: nil),
            Action(text: "Yes", handler: { [weak self] in
                //use self in here..
            })
        ])
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class MyViewController : UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        let alert = TextAlertView()
        view.addSubview(alert)
        self.view = view
    }
}

Every time I create an instance TextAlertView, it crashes super.initwith bad access. However, if I changed:

Action(title: "Yes", { [weak self] in
    //use self in here..
})

at

Action(title: "Yes", {
    //Blank.. doesn't reference `self` in any way (weak, unowned, etc)
})

it works!

Is there a way to refer to selfbeing weak or not inside the action block during super-initialization (in the above example, am I doing this in a parameter super.init?

The code compiles .. it just crashes accidentally at runtime.

+4
source share
1 answer

Short answer :

self super.init. "" self super.init .

, , , self self, self .

self , strong/weak , self ( ). .


" self " - self , self :

let myProperty: String

init(with myProperty: String) {
    // this usage of self is allowed
    self.myProperty = myProperty
    super.init(nibName: nil, bundle: nil)
}

:

documentation:

4

- , , .

super.init,

:

1

.

. .

, , , . .

.

, .

, , , , 1 .

, super.init self :

2

, . , ..

, self.

, , self , . , - , , .

:

Action(title: "Yes", {
    //Blank.. doesn't reference `self` in any way (weak, unowned, etc)
})

self, . self. , self, :

enter image description here

, , self , super.init, self, .

+6

Source: https://habr.com/ru/post/1694147/


All Articles