Exploring Different Data Observers and Use Cases with Code

Exploring Different Data Observers and Use Cases with Code

1. Protocol/Delegate Pattern:

🔍 Understanding the Scenario: Suppose we have a scenario where we need to notify a ViewController whenever a new item is added to a shopping cart. We'll use the protocol/delegate pattern to achieve this.

📝 Protocol Definition:

protocol ShoppingCartDelegate: AnyObject {
    func didAddItemToCart(itemName: String)
}

🛒 Shopping Cart Class:

class ShoppingCart {
    weak var delegate: ShoppingCartDelegate?

    func addItemToCart(itemName: String) {
        // Add item to cart logic
        delegate?.didAddItemToCart(itemName: itemName)
    }
}

👩‍👧‍👦 View Controller Implementation:

class ViewController: UIViewController, ShoppingCartDelegate {
    let shoppingCart = ShoppingCart()

    override func viewDidLoad() {
        super.viewDidLoad()
        shoppingCart.delegate = self
    }

    func didAddItemToCart(itemName: String) {
        // Update UI or perform actions when an item is added to the cart
        print("Item added to cart: \(itemName)")
    }
}

2. Closure-based Observers:

🔍 Understanding the Scenario: Let's consider a scenario where we want to observe changes in a user's location using closures.

🌍 Location Manager Class:

class LocationManager {
    var onLocationUpdate: ((Double, Double) -> Void)?

    func startUpdatingLocation() {
        // Start location updates
        // Simulated location update
        let latitude = 37.7749
        let longitude = -122.4194
        onLocationUpdate?(latitude, longitude)
    }
}

🗺 View Controller Implementation:

class ViewController: UIViewController {
    let locationManager = LocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        locationManager.onLocationUpdate = { latitude, longitude in
            // Handle location update
            print("New location - Latitude: \(latitude), Longitude: \(longitude)")
        }

        // Start observing location updates
        locationManager.startUpdatingLocation()
    }
}

3. NSNotification Mechanism:

🔍 Understanding the Scenario: Suppose we need to notify multiple parts of our application when the user's authentication status changes. We'll use NSNotification to broadcast this information.

🔐 Authentication Manager Class:

class AuthenticationManager {
    static let authenticationStatusChangedNotification = Notification.Name("AuthenticationStatusChanged")

    func simulateAuthenticationStatusChange() {
        // Simulated authentication status change
        NotificationCenter.default.post(name: AuthenticationManager.authenticationStatusChangedNotification, object: nil)
    }
}

🔓 View Controller Implementation:

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        
        NotificationCenter.default.addObserver(self, selector: #selector(authenticationStatusChanged), name: AuthenticationManager.authenticationStatusChangedNotification, object: nil)
    }

    @objc func authenticationStatusChanged() {
        // Handle authentication status change
        print("Authentication status changed.")
    }
}

These examples showcase how to use different data observer patterns in iOS development, each with its unique strengths and use cases. Whether you prefer the protocol/delegate pattern, closure-based observers, or NSNotification mechanism, understanding these concepts is essential for building robust and efficient iOS applications.

Comments

Popular posts from this blog

🌐✨ Top 10 Websites for Web Development You Need to Know as a Web Developer! 💻🚀

Top 10 Chrome Extensions for Developers

Comparing Filter, Map, and Find in Swift and JavaScrip