Clicky

iOS Dev Nugget 268 Using Blocks for Delegate Methods

.

Need to run a code review on your codebase? Hire me

One of the most common way to reduce coupling when creating a new class is to create a delegate(s) for it. This is a common pattern used in Cocoa (Touch) classes, from simple examples like UIImagePickerController and UIImagePickerControllerDelegate to more complicated examples like UITableView and UITableViewDelegate, and UITableViewDataSource.

You can implement delegates using protocols. e.g.

protocol DelegateOfA {
    func onSomethingHappened()
}

class A {
    var delegate: DelegateOfA?

    init() {}
    func doSomething() {}
}

Use them like this:

class SomeDelegate: DelegateOfA {
    func onSomethingHappened() {
        print("I know something happened")
    }
}

let aDelegate = SomeDelegate()

let a = A()
a.delegate = aDelegate
a.doSomething()

//And this may/will be invoked somehow and fire your delegate methods:
//a.delegate?.onSomethingHappened()

One thing I have done more recently is to use blocks for these delegates:

class A {
    var onSomethingHappened: (()->())?

    init() {}
    func doSomething() {}
}

Use it like this:

let a = A()
a.onSomethingHappened = {
    print("I know something happened")
}
a.doSomething()

//And this may/will be invoked somehow and fire your delegate blocks:
a.onSomethingHappened?()

The overall code is slightly shorter, but more importantly, both the object creation of A and the delegate code are close together, making it easier to read, understand and maintain.

Try it out!

Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No

.

.

Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter

.

View archives of past issues