Skip to main content

Property observers: didSet và willSet trong Swift

Property observers: didSet và willSet trong Swift

Chúng ta đã biết là trong Swift đã có tính năng getter, setter với keyword là get, set cho thuộc tính. Ngoài ra, Swift còn có thêm tính năng là Property Observers. Tiếng Việt là dịch ra là quan sát/theo dõi thuộc tính.

Cái tên đã nói nên tính cách rồi, Property Observers tức là theo dõi sự thay đổi của thuộc tính, nhất cử nhất động của thuộc tính ta đều biết.
Trong quyển Start with Why?, điều quan trọng nhất không phải là biết cách làm mà quan trọng nhất là tại sao phải làm?
Vậy tại, why, vì lý do gì mà phải sử dụng willSet, didSet?. Dưới đây là những lý do mình thấy hay sử dụng didSet, willSet nhất:
  • Cập nhật lại UI khi data thay đổi, tiết kiệm vài dòng code.
  • Áp dụng để xây dựng các kiến trúc phần mềm, chẳng hạn như mô hình MVVM. Sơ qua MVVM là do Microsoft sáng tạo ra, nó dựa vào cơ chế data binding 2 chiều. Mà bên Swift không có nên đã chế ra Key-Value-Observing. Và didSet, willSet sẽ giúp thực hiện điều này
  • Xây dựng các custom control.

Ví dụ minh họa:

didSet và willSet trong Swift



https://gist.github.com/KhoaVanNguyen/1310b52158cb9292cfb867b61dafe932
Có hai loại property observer: willSet và didSet được gọi trước và sau khi giá trị thay đổi. Ở willSet bạn sẽ có thêm một giá trị là newValue - chỉ được sử dụng trong scope của willSet, còn didSet bạn sẽ có thêm oldValue - chỉ được sử dụng trong scope của didSet
Như ở ví dụ trên, mình đã sử dụng newValue trong willSet. Nhờ cơ chế này mà bạn không phải thay đổi UI mỗi lần dữ liệu thay đổi mà chỉ cần thay đổi biến age như trên.
Với ví dụ trên, dữ liệu chỉ thay đổi khi nhấn Button, tuy nhiên khi thực tế với những app phức tạp khi mà dữ liệu thay đổi nhiều, việc xử dụng didSet, willSet sẽ có hiệu quả.
Link github project:
https://github.com/KhoaVanNguyen/Swift-Tutorials

//
//  didSetwillSetVC.swift
//  didSetwill
//
//  Created by Khoa on 12/7/16.
//  Copyright © 2016 Khoa. All rights reserved.
//

import UIKit
class ViewController: UIViewController {

    
    var age: Int = 0 {
        willSet {
            if (age >= 100) {
                showAlert(title: "Error", message: "Bạn đã \(newValue) tuổi, quá già để xử dụng app của chúng tôi")
            }
        }
        didSet {
            if ( age > 10 && age < 100){
                ageLbl.text = "age: \(age)"
            }
        }
    }
    @IBOutlet weak var ageLbl: UILabel!
    @IBOutlet weak var ageTF: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    @IBAction func changeBtn(_ sender: Any) {
        guard let userAge = ageTF.text else {
            return
        }
        age = Int(userAge)!
    }
    func showAlert(title: String, message : String){
        
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
        
        alert.addAction(okAction)
        
        present(alert, animated: true, completion: nil)
        
    }

}

Comments

Popular posts from this blog

RxSwift - Giới thiệu

Bạn có nghe qua về Reactive Programming chưa, đây là một khái niệm lập trình hoàn toàn mới. “Reactive Programming là lập trình theo hướng bất đồng bộ các dòng chảy dữ liệu(data streams)” Sau khi đọc khái niệm các bạn có lẽ rất mơ hồ, vậy các data streams là gì. Vậy để mình ví dụ cho các bạn: - Trong lập trình bình thường ( imperative programming ) a = b + c , tức a được gắn với kết quả cộng của b và c .Khi b với c thay đổi thì tất nhiên sẽ không ảnh hưởng tới a, nhưng trong Reactive Programming này a sẽ tự động thay đổi khi b hoặc c thay đổi, kết quả của a sẽ lập tức thay đổi theo. Vậy tại sao nên dùng RXSwift: + Giúp ứng dụng của bạn hoạt động 1 cách như là real time update ui khi có thay đổi data flow, mang đến trải nghiệm tuyệt vời cho User. + Dễ dàng lập trình bất đồng bộ (Async) thay vì phải dùng : callbacks, delegates, notifications, kvo… Bạn phải dùng nhiều thứ gây ra ứng dụng của bạn phức tạp, khó kiểm soát. + Chuyển đổi các thread khi thực hiện 1 cách...

Swift GCD part 1: Thread safe singletons

Preview Singletons are entities, referenced to the same instance of a class from everywhere in your code. It doesn't matter if you like them or not, you will definitely meet them, so it's better to understand how they work. Constructing and handling a set of data doesn't seem to be a big challenge at first glance. The problems appear when you try to optimise the user experience with background work and your app starts acting weird. ??‍♂️ After decades of watching your display mostly with a blank face, you finally realize that your data isn't handled consistently by the manager because you're accessing it (running tasks on it) from multiple threads at the same time. So you really do have to deal with making your singletons thread safe. This article series is dedicated to thread handling using Swift. In the first part below you will get a comprehensive insight into som...

Enum Initializers

In Swift Talk 45 , we wrote a small library for parsing routes. We represented routes as enums, and added a custom initializer to parse routes: enum Route { case home case users(id: Int ) } extension Route { init ?(path: String ) { if path == "/" { self = .home } else if path.hasPrefix( "/users" ) { self = .users(id: 1 ) } else { return nil } } } Of course, this code isn’t complete (see the full public episode for that). Today, we want to focus on assigning to self inside the initializer. In the initializer of any struct or enum we can treat self as a mutable variable (as if it were declared using inout ). This is why we can do the following: enum Result < A > { case success( A ) case error( Error ) } extension Result { init ( _ value: A ) { self = .success(value) } } We can even do this in a struct, although it’s easie...