If I want to reuse a protocol to notify the master view controller of when the detail view controller is dismissed such as this: UIView notification when modal UIImagePickerController is dismissed?
where would i declare this protocol? Is it best practices to keep protocols in separate files? Thanks.
Protocols are implemented in the classes conforming to the protocol. A simple example would be a network URL handling class, it will have a protocol with methods like processCompleted delegate method that intimates the calling class once the network URL fetching operation is over. A syntax of protocol is shown below.
In Swift, calling a method will be decided at compile time and is similar to object-oriented programming, whereas in Objective C, calling a method will be decided at runtime, and also Objective C has special features like adding or replacing methods like on a class which already exists.
The goal of the @property directive is to configure how an object can be exposed. If you intend to use a variable inside the class and do not need to expose it to outside classes, then you do not need to define a property for it. Properties are basically the accessor methods.
An Objective-C delegate is an object that has been assigned to the delegate property another object. To create one, you define a class that implements the delegate methods you're interested in, and mark that class as implementing the delegate protocol.
Typically I (copying Apple's methods) declare protocols on the header of the class that will be interacting with delegates of that protocol. (E.g. the UIActionSheet header file holds the protocol declaration for UIActionSheetDelegate.) It doesn't really matter technically where you declare protocols, as long as you don't have a circular reference of #import
statements. This won't normally happen because the class that interacts with the protocol does so to avoid needing to #import
all of the other classes that will now implement the protocol. (UIActionSheet sends messages to your classes when it is dismissed through the protocol, and therefore doesn't need to #import any of your classes.)
If you have a protocol and several unrelated classes will be interacting with delegates of that protocol, that would be a good indicator to put the protocol in its own file, because the protocol isn't really associated with one particular class.
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