Understanding Self Reference

Asked 2 years ago, Updated 2 years ago, 150 views

https://developer.apple.com/library/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson3.html#//apple_ref/doc/uid/TP40015214-CH22-SW1

In the iOS Developer Library swift tutorial Connect the UI to Code chapter, there was something I didn't understand about delete, so I would like to ask you a question.

import UIKit
    classViewController:UIViewController, UITextFieldDelegate{

    @IBOutlet weak var nameTextField: UITextField!
    @IBOutlet weak var mealNameLabel: UILabel!

    override func viewDidLoad(){
        super.viewDidLoad()
        nameTextField.delegate=self

    functextFieldShouldReturn(textField:UITextField) - >Bool{
        textField.resignFirstResponder()
        return true
    }

    functextFieldDidEndEditing (textField:UITextField) {
        mealNameLabel.text=textField.text
    }

    @ IBAction funcsetDefaultLabelText (sender: UIButton) {
        mealNameLabel.text="Default Text"
    }

    override funcdidReceiveMemoryWarning(){
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }    

}

I understand that ViewController means delete text field.

nameTextField.delegate=self

So,

nameTextField.delegate=ViewController()

When I rewritten it, there was no error on the code, but the simulator did not change the label when I typed characters in the text field and pressed the return key.

What does this self refer to?

swift swift2 delegate

2022-09-29 21:26

1 Answers

First, understand the relationship between classes and instances.

A class is just a design document, and an instance is like a robot built on that design document."Instantization" or "Create Instance" means that you are making a new robot.

Based on the above, what self refers to is "the robot itself executing the instruction at that time."

nameTextField.delegate=self

The robot executing the command at that point sets itself as a delete.The robot has its own view that is displayed on the screen, and after the iOS system manufactures the robot, it needs an instance of @IBOutlet (this is another robot, though of a different kind).I'm giving it to you.

However,

nameTextField.delegate=ViewController()

This is the same type of robot called ViewController, but it is a completely different robot from the one currently in charge of displaying the screen.Unlike robots created by iOS, @IBOutlet of robots created by designating the initializer directly does not automatically set anything.

Do you understand what's going on?

Some people find the "robot" metaphor rather difficult to understand.If you have any questions or concerns, please let us know in your comments.


2022-09-29 21:26

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.