Whenever I create an init that has a delegate conforming to a protocol I write the init as this:
- (id)initWithDelegate:(id<ProtocolToConform>)delegate;
This way I will have a warning if the creating object does not conform to the protocol.
However I noticed that ie UIAlertView
init method looks like this:
- (id)initWithTitle:(NSString *)title message:(NSString *)message delegate:(id)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ...
The delegate argument does not specify to conform to the UIAlertViewDelegate
protocol? Any clues why Apple has done it that way?
Protocol: A set of methods that would be implemented by the class which conforms to that protocol. Delegate: The reference to that class which conforms to the protocol and will adhere to implement methods defined in the protocol.
Key Steps to DelegationCreate a delegate protocol that defines the messages sent to the delegate. Create a delegate property in the delegating class to keep track of the delegate. Adopt and implement the delegate protocol in the delegate class. Call the delegate from the delegating object.
Delegates are a design pattern that allows one object to send messages to another object when a specific event happens. Imagine an object A calls an object B to perform an action.
For safety reasons, Swift always makes you call super. init() from child classes – just in case the parent class does some important work when it's created. SPONSORED Get complete control over your app releases with Runway. Ship more confidently from kickoff to rollout with centralized collaboration and automation.
Good question! I do the same thing in the hope of catching more errors at compile time.
Apple appear to be conforming to their own standards; as stated in Concepts in Objective-C:
To implement a delegate for your custom class, complete the following steps:
Declare the delegate accessor methods in your class header file.
- (id)delegate;
- (void)setDelegate:(id)newDelegate;
Implement the accessor methods. In a memory-managed program, to avoid retain cycles, the setter method should not retain or copy your delegate.
- (id)delegate {
return delegate;
}
- (void)setDelegate:(id)newDelegate {
delegate = newDelegate;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With