Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

where to declare protocols for reuse in objective-c

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.

like image 307
Crystal Avatar asked Jun 01 '12 02:06

Crystal


People also ask

How do you write a protocol in Objective-C?

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.

What is the difference between Swift protocol and Objective-C protocol?

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.

What is @property in Objective-C?

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.

What is delegate in Objective-C?

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.


1 Answers

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.

like image 119
Alex Gosselin Avatar answered Oct 16 '22 23:10

Alex Gosselin