Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

init with delegate protocol

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?

like image 718
Peter Warbo Avatar asked Jan 31 '13 13:01

Peter Warbo


People also ask

What is delegate protocol?

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.

How do I use protocol and delegate in Swift 4?

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.

How do you declare a delegate in Swift?

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.

Why we use super init in Swift?

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.


1 Answers

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;
}
like image 132
trojanfoe Avatar answered Oct 20 '22 05:10

trojanfoe