iOS Delegates Tutorial
Key Steps to Delegation
The delegation design pattern has long been a core competency for Cocoa programmers. This remains the case with the arrival of Swift. Regardless of whether you are using Objective-C or Swift the basic steps to use delegation are the same:
- Create a delegate protocol that defines the responsibilities of the delegate.
- Create a delegate property in the delegating class to keep track of the delegate.
- Adopt and implement the delegate methods in the delegate class.
- Call the delegate from the delegating object.
Note that there are a couple of differences between Swift and Objective-C support for delegates:
- Swift allows protocols to be used by classes, structs or enums. In Objective-C we are limited to classes. This changes whether we use reference semantics (classes) or value semantics (structs and enums) for the delegate.
- Objective-C supports optional protocol methods. Swift only allows optional protocol requirements if you mark the protocol with the @objc attribute. If you use @objc you can then only use the protocol with class types.
Create the Delegate Protocol
Let’s create a delegate protocol that a view controller might use to tell a parent or master view controller that a task has finished.
In Objective-C:
@protocol DetailViewControllerProtocol <NSObject>
- (void)didFinishTask:(DetailViewController *)sender;
@end
The Swift code is similar:
protocol DetailViewControllerDelegate: class {
func didFinishTask(sender: DetailViewController)
}
Notes:
- The class keyword in the Swift protocol definition limits protocol adoption to class types (and not structures or enums). This is important if we want to use a weak reference to the delegate as will see next.
- I changed the above code to include the sender in the delegate message as is common practise (thanks to @salutis for keeping me straight).
Add a Delegate Property
Our delegating class needs a reference to the delegate - but should it be a strong or weak reference? We need to pay attention not to create a retain cycle between the delegate and the delegating objects. That can happen if our delegate already has a strong reference to our delegating object. In that case we should make our delegate a weak reference. In Objective-C we do that as follows:
@property (weak) id<DetailViewControllerProtocol>delegate;
Since we do not always set a delegate we use an optional property in Swift:
weak var delegate:DetailViewControllerDelegate?
Notes:
- The use of a weak delegate in Swift is only allowed when we have a class protocol. Xcode will complain if you try to use a weak reference to a non-class protocol since structures and enums use value not reference semantics.
- Using an optional type for the delegate in Swift also means it is automatically set to nil.
Adopt and implement the Delegate Protocol
In our delegate class we tell the compiler that we are adopting the protocol and then implement the delegate method(s). In Objective-C we can use a category to declare the protocol conformance:
@interface MasterViewController () <DetailViewControllerDelegateProtocol>
@end
- (void)didFinishTask:(DetailViewController *)sender {
// do stuff like updating the UI
}
For the Swift equivalent code we can use an extension to the master view controller class to declare and implement the delegate function:
extension MasterViewController: DetailViewControllerDelegate {
func didFinishTask(sender: DetailViewController) {
// do stuff like updating the UI
}
}
We also need to remember to set the delegate somewhere. This might be in a prepareForSegue or target-action method that will present the detail view controller:
// Objective-C
detailViewController.delegate = self;
// Swift
detailViewController.delegate = self
Calling Delegate Methods
Finally we can call the delegate from our delegating class. In Objective-C we avoid checking the delegate is set since sending a message to nil does no harm. (If you have optional methods use respondsToSelector: to first test if it is implemented by the delegate):
[self.delegate didFinishTask:self];
In Swift we can use optional chaining to achieve a similar effect. Only if the delegate is not nil do we call the delegate method:
delegate?.didFinishTask(self)
This comment has been removed by the author.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteHas anyone used App On Radar for their app development needs? I'm looking for honest opinions about their services. How was your experience working with them? Did they deliver on their promises? Your insights would be invaluable!
ReplyDeleteGreat article! I remember being completely captivated by my first animated film—it felt like magic seeing characters and worlds come to life. Animation has this unique ability to convey deep emotions and tell stories in ways that live-action sometimes can't. By the way, if you're into high-quality animation, you should definitely check out Tenfold Animation. Their work is absolutely stunning and really pushes the creative envelope. Keep up the fantastic content!
ReplyDeleteGreat insights on business financial strategies! Wolfgang Zulauf's expertise in the field is truly impressive, providing valuable guidance for navigating complex financial landscapes. His approach is a must-follow for anyone looking to optimize their financial operations.
ReplyDeleteDelegation design pattern is something important for Cocoa developers, and mastering it means just as much in Swift. The clear breakdown into steps really highlights its applicability and how well this bridges both languages. Now, flexibility with protocols is a game-changer by Swift. For those who juggle studies might feel this complex—makes you think if you could hire someone to take my exam to free up the time!
ReplyDeleteYour team provides outstanding support through tailored online book promotion services, helping authors build strong visibility across digital platforms. With smart strategies and targeted outreach, you connect books with the right readers. Highly effective and highly recommended for authors looking to grow online!
ReplyDeleteGreat explanation of iOS delegation in both Swift and Objective-C — it really clarifies how to avoid retain cycles and implement weak references properly. For students preparing for iOS development exams or certifications visit Do My Online Exam For Me we offer online exam help certifications, and classes to strengthen your programming Services 🚀
ReplyDeleteFantastic tutorial! 👏 Your detailed explanation of iOS delegation in both Swift and Objective-C makes it much easier for developers to implement delegate patterns correctly. For those looking to deepen their iOS development skills and learn more about app development, UI design, and digital strategies, check out my website digital marketing services houston for helpful guides and resources.
ReplyDeleteGreat tutorial on iOS delegates! Very clear and helpful for understanding this fundamental concept. Thanks for sharing! – David McKay Publications - DavidMcKayPublications
ReplyDelete