Why would you want a class to conform to a protocol privately? - objective-c

I've been looking at Apple's MVCNetworking example project and part of the interface definition for AppDelegate is puzzling me. In the .h file we have this:
#interface AppDelegate : NSObject
{
...
But in the .m file we have this:
#interface AppDelegate () <SetupViewControllerDelegate>
...
So this class is privately conforming to the protocol. But why would you want to do this instead of publicly declaring it in the header?

In general, you should publicly expose as little as possible. The fact that the AppDelegate can be a SetupViewController's delegate is probably used when the AppDelegate presents a SetupViewController. No other class should be setting the AppDelegate as some other SetupViewController's delegate, so it wouldn't make sense to publicly advertise that conformance.

It looks like the implementation uses a SetupViewController internally in one of its "private" methods presentSetupViewControllerAnimated:. Since the view controller is not publicly accessible (through a property or otherwise), there's no need to declare the class as conforming to the protocol from the public point of view. In other words, the protocol is related only to the implementation of the class, and not to the public interface that it presents.

There are times where you want to be a delegate for another object, but in so doing you may get compiler warnings because you aren't explicitly declaring that your class conforms to the required methods of the protocol. As others have mentioned, one of the pillars of Object Oriented programming is information hiding. It is not desirable to declare in your header that a class implements a particular protocol because you would be breaking that principle. It also opens your class to abuse or to be used in ways it was not intended because it is making that information known to other classes. By declaring a private category in the .m file and letting the compiler know of your intention to implement this protocol, you not only get rid of the warnings that may crop up, but you are, in effect, making your code self-documenting.

Maybe because you don't want anybody to know about your protocol with except yourself. So no somebody externally of AppDelegate will pass instance of Appdelegate as delegate to another class instance. So you will able to pass it as this internally.

Related

Who does what with protocols in objective-c?

Trying to understand protocols and their use... having a hard time of it. The more I read, the less I am able to even formulate questions about them. I've read the statement "a protocol is a contract" a hundred times, but it just doesn't click.
I "only" want to develop really simple apps, so assume that I would not myself create a protocol for any of my classes.
I do want to use Apple's Scenekit framework, for example, and understand that I am required to implement some methods to do this - for example the SCNSceneRendererDelegate. The compiler enforces this, and it knows to do that because in my header file I have inserted:
#interface AAPLGameViewController : UIViewController <SCNSceneRendererDelegate>
the bit between the angle brackets specifically.
For the prototypes of the functions I have to implement, I go look for a
#protocol
...
#end
section in the SCNSceneRendererDelegate header file.
But now I've come across some #protocol sections (e.g. in the UIApplication header file) that contain #properties!! I thought #protocol was only about implementing certain methods, what is a property doing there?
I also came across in one of the answers here that specifying a protocol name when creating an instance of an object allows me to use objects that I know nothing about. I would be very grateful to get a few simple practical examples of where this would be useful.
And finally, in Java, the counterpart to (Obj-C) #protocols are called interfaces. Is there a counterpart in Java to (Obj-C) #interface?
Thanks much, cheers.
Adhering to a protocol tells other classes that your class has a specific set of characteristics. Usually protocols are used to define what methods a specific class should have so that it can be the delegate of another class, meaning the class adopting the protocol is guaranteed to have defined the required methods that the delegate class will call in a callback. If the protocol defines a property, it simply means any classes adopting the protocol are expected to also have that property. For example:
#protocol MyProtocol <NSObject>
#required
#property (readonly) NSString *title;
#optional
- (void) someMethod;
#end
I can now define a method anywhere that takes an object conforming to MyProtocol and safely access the title property because it is guaranteed to exist for all classes adopting MyProtocol.
-(void)printTitleOfObject:(id<MyProtocol>)object {
NSLog(#"%#", object.title);
}
So even though id can be any object, since we know that it conforms to our protocol we know that it has the title property. When people say "a protocol is a contract", what they mean is even if we don't know specifically what class is adopting the protocol, we know it at least has the methods and properties listed as required in the protocol. Specifying a protocol for a class allows us to know some information about it, even if we don't know what class it is.
Apple has written documentation for protocols they've written, like the SCNSceneRendererDelegate you mentioned in your question.
But now I've come across some #protocol sections (e.g. in the
UIApplication header file) that contain #properties!! I thought
#protocol was only about implementing certain methods, what is a
property doing there?
Properties are methods. A property declaration is simply a declaration for a getter-setter method pair (or if a readonly property, just a getter method), and allows the compiler to turn a dot notation access into a call to this getter and setter. That's all a property is. How the getter/setter is implemented (whether manually implemented or synthesized), and whether it reflects an underlying value or not (or is computed from other things) are private implementation details of the getter/setter methods.

Objective C class declaration syntax

I need some help with understanding the class declaration syntax in Objective C,
or to be more specific
#interface SomeViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate>
what does UITableViewDataSource,UITableViewDelegate mean
My understanding is that it receives these two objects when the class is instantiated.Correct me if I am wrong..
UITableViewDataSource and UITableViewDelegate are two protocols, not classes (or objects).
When you declare a class, you can specify any number of protocols that your class implements using the < > bracket syntax.
A protocol is a list of required or optional methods. Adding the protocol to the class declaration doesn't actually implement or declare any of the methods in that protocol. You have to do that yourself. However if you don't implement a required protocol method, you will get a compiler warning.
When you declare a class, the <> syntax allows you to specify a list of protocols the class must comply with.
A protocol is a "set" of methods that your class must implement (You can specify optional methods too). They only have method declarations, but the programmer must implement them in his classes. Protocols are really important in Objective-C since they are the heart of the delegation pattern.
In this specific case, UITableViewDelegate is a protocol that an object that deals with UITableViews must comply with. Table View delegates are responsible for controlling the table and it's cells, such as setting their heigh, accesories, etc.
UItableViewDataSource is a protocol an object that gives data to a table view must comply with. An object complying with this protocol is responsible for returning the data that will be displayed in a table view.
Not using the protocols when needed can create warnings that will sooner or later crash your app.
UITableViewDataSource and UITableViewDelegate are protocols. To understand what protocol is see this. Protocols are similar to interface in Java.
#interface SomeViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate>
This line just means that you declare a class "SomeViewController" which inherits from "UITableViewController" and adopts two protocols: UITableViewDataSource and UITableViewDelegate

How to find out whether a given class serves as a delegate for an object?

In Objective-C, how can one find out whether a given class serves as a delegate for a given type of an object?
A book i am reading suggest examining the .h file, however i am not sure exactly what to look for. How would .h file declare that it's .m is a delegate for some object?
Please clarify.
If the delegating class has a protocol for its delegate, you could check whether the class conforms to that protocol. Otherwise, look for the methods that the delegate is supposed to implement (e.g. the tableView:…: family of methods for an NSTableView delegate).

How do I discover which messages a delegate can / should implement?

In Objective-C / Cocoa how do I discover the messages I can implement in a delegate class?
From what I have read in the documentation a class will only allow certain chosen messages to be handled via a delegate but so far have found difficulty finding a list of messages for a class.
To ask the question another way, if I created a delegate for NSApplication, which messages are available for me to handle?
The documentation for NSApplication states a delegate
responds to certain messages on behalf of NSApp.
The documentation then goes onto say
NSApplication defines over twenty delegate methods that offer opportunities for modifying specific aspects of application behavior.
but as far as I can see it fails to list these methods / messages so how do I know which ones will be called from my delegate?
The delegate is usually supposed to conform to a protocol declared for that purpose, e.g. NSApplicationDelegate. If it's not clearly spelled out already, you can often find the name of the appropriate protocol by looking at the type of the delegate property (in this case, id<NSApplicationDelegate>). You can check the documentation for details on the methods, or the #protocol declaration in the appropriate header file for specifics on which methods are available and which are required or optional.
There are some cases where the object does not define a protocol for its delegate, for example NSURLConnection. In this case, you just have to follow the documentation of the class with respect to what it expects of its delegate.
In either case, it is completely up to the class when it sends a message to the delegate and what the semantics of any message are.
These methods are described in the NSApplicationDelegate documentation:
http://developer.apple.com/library/mac/#documentation/cocoa/reference/NSApplicationDelegate_Protocol/Reference/Reference.html
One quick note that is that it is useful to understand the difference between formal and informal protocols. Also formal protocols have optional methods, which needn't be called.
When you write your own protocol you will want to check -respondsToSelector: before sending optional/informal methods.
formal protocols are defined like...
#protocol SomeProtocol <NSObject>
-(void)someMethod:(id)sender;
-(void)someOtherMethod:(NSString*)aString;
#property(nonatomic,retain) someProperty;
#optional
-(BOOL)someOptionalMethod;
#end
and are adopted like...
#interface SomeClass : NSObject <SomeProtocol> {
}
#end
this tells the compiler that you are adopting SomeProtocol, and you wont be required to declare you methods for the protocol in the .h file, it also tell the compiler to warn you if you haven't implemented all of the required methods.
for informal protocols you don't adopt them syntactically, but you will need to declare your methods in the .h file.

Defining categories for protocols in Objective-C?

In Objective-C, I can add methods to existing classes with a category, e.g.
#interface NSString (MyCategory)
- (BOOL) startsWith: (NSString*) prefix;
#end
Is it also possible to do this with protocols, i.e. if there was a NSString protocol, something like:
#interface <NSString> (MyCategory)
- (BOOL) startsWith: (NSString*) prefix;
#end
I want to do this since I have several extensions to NSObject (the class), using only public NSObject methods, and I want those extensions also to work with objects implementing the protocol .
To give a further example, what if I want to write a method logDescription that prints an object's description to the log:
- (void) logDescription {
NSLog(#"%#", [self description]);
}
I can of course add this method to NSObject, but there are other classes that do not inherit from NSObject, where I'd also like to have this method, e.g. NSProxy. Since the method only uses public members of protocol , it would be best to add it to the protocol.
Edit: Java 8 now has this with "virtual extension methods" in interfaces: http://cr.openjdk.java.net/~briangoetz/lambda/Defender%20Methods%20v4.pdf. This is exactly what I would like to do in Objective-C. I did not see this question earning this much attention...
Regards,
Jochen
Short answer: No.
Long answer: how would this work? Imagine you could add methods to existing protocols? How would this work? Imagine we wanted to add another method to NSCoding, say -(NSArray *) codingKeys; This method is a required method that returns an array of the keys used to encoding the object.
The problem is that there are existing classes (like, say NSString) that already implement NSCoding, but don't implement our codingKeys method. What should happen? How would the pre-compiled framework know what to do when this required message gets sent to a class that does not implement it?
You could say "we can add the definition of this method via a category" or "we could say that any methods added via these protocol categories are explicitly optional". Yes, you could do this and theoretically get around the problem I've described above. But if you're going to do that, you might as well just make it a category in the first place, and then check to make sure the class respondsToSelector: before invoking the method.
While it's true that you can't define categories for protocols (and wouldn't want to, because you don't know anything about the existing object), you can define categories in such a way that the code only applies to an object of the given type that has the desired protocol (sort of like C++'s partial template specialization).
The main use for something like this is when you wish to define a category that depends on a customized version of a class. (Imagine that I have UIViewController subclasses that conform to the Foo protocol, meaning they have the foo property, my category code may have need of the foo property, but I can't apply it to the Foo protocol, and if I simply apply it to UIViewController, the code won't compile by default, and forcing it to compile means someone doing introspection, or just screwing up, might call your code which depends on the protocol. A hybrid approach could work like this:
#protocol Foo
- (void)fooMethod
#property (retain) NSString *foo;
#end
#implementation UIViewController (FooCategory)
- (void)fooMethod {
if (![self conformsToProtocol:#protocol(Foo)]) {
return;
}
UIViewController<Foo> *me = (UIViewController<Foo>*) self;
// For the rest of the method, use "me" instead of "self"
NSLog(#"My foo property is \"%#\"", me.foo);
}
#end
With the hybrid approach, you can write the code only once (per class that is supposed to implement the protocol) and be sure that it won't affect instances of the class that don't conform to the protocol.
The downside is that property synthesis/definition still has to happen in the individual subclasses.
extObjC has the NEATEST stuff you can do with Protocols / Categories... first off is #concreteprotocol...
Defines a "concrete protocol," which can provide default implementations of methods within protocol.
An #protocol block should exist in a header file, and a corresponding #concreteprotocol block in an implementation file.
Any object that declares itself to conform to this protocol will receive its method implementations, but only if no method by the same name already exists.
MyProtocol.h
#protocol MyProtocol
#required - (void)someRequiredMethod;
#optional - (void)someOptionalMethod;
#concrete - (BOOL)isConcrete;
MyProtocol.m
#concreteprotocol(MyProtocol) - (BOOL)isConcrete { return YES; } ...
so declaring an object MyDumbObject : NSObject <MyProtocol> will automatically return YES to isConcrete.
Also, they have pcategoryinterface(PROTOCOL,CATEGORY) which "defines the interface for a category named CATEGORY on a protocol PROTOCOL". Protocol categories contain methods that are automatically applied to any class that declares itself to conform to PROTOCOL." There is an accompanying macro you also have to use in your implementation file. See the docs.
Last, but NOT least / not directly related to #protocols is
synthesizeAssociation(CLASS, PROPERTY), which "synthesizes a property for a class using associated objects. This is primarily useful for adding properties to a class within a category. PROPERTY must have been declared with #property in the interface of the specified class (or a category upon it), and must be of object type."
So many of the tools in this library open (way-up) the things you can do with ObjC... from multiple inheritance... to well, your imagination is the limit.
It isn't really meaningful to do so since a protocol can't actually implement the method. A protocol is a way of declaring that you support some methods. Adding a method to this list outside the protocol means that all "conforming" classes accidentally declare the new method even though they don't implement it. If some class implemented the NSObject protocol but did not descend from NSObject, and then you added a method to the protocol, that would break the class's conformance.
You can, however, create a new protocol that includes the old one with a declaration like #protocol SpecialObject <NSObject>.
I think you may be mixing up terms here and there. Extensions, Categories, Protocols, Interfaces and Classes are all different things in Objective-C. In The Objective-C 2.0 Language Apple describes the differences very well, including the benefits and drawbacks to using categories and extensions.
If you think about it, what is a "Category" or "Extension" in the conceptual sense? It's a way of adding functionality to a Class. In Objective-C, protocols are designed to have no implementation. Therefore, how would you add or extend the implementation of something that doesn't have implementation to begin with?
if you're already writing a category, why not just add in the protocol definition in the header right after the category definition?
i.e.
#interface NSString (MyCategory)
- (BOOL) startsWith: (NSString*) prefix;
#end
#protocol MyExtendedProtocolName <NSString>
//Method declarations go here
#end
this way any class that imports the category header will also get the protocol definition, and you can add it into your class..
#interface MyClass <OriginalProtocol,MyExtendedProtocolName>
also, be careful when subclassing NSString, it's a cluster and you may not always get the behaviour you're expecting.
Adam Sharp posted a solution that worked for me.
It involves 3 steps:
Defining the methods you want to add as #optional on a protocol.
Making the objects you want to extend conform to that protocol.
Copying those methods into those objects at runtime.
Check out the link for the full details.