Understanding #Protocols in Objective-C - iphone

I am a beginner to programming, and a beginner to Objective-C. I learned basic C and decided to start learning Objective-C. I am reading "Programming in Objective C 2.0" by Steven Kochan.
His section on Protocols is vague. He doesn't thoroughly explain WHY someone would want to use protocols in their programs, nor does he give a concrete example with it implemented in a program.
He writes:
"You can use a protocol to define methods that you want other people who subclass your class to implement."
He also says that Protocols are good for sub-classes to be able to implement certain methods, without having to first define the actual methods. He also says protocols can be used across different classes because they are classless.
I know there must be a valid and smart way to implement protocols, but based on what he wrote, I don't see why someone would use protocols instead of just creating a class method outside of the reason that more than one class can adhere to a protocol (I know there are some more good reasons though!).
I was wondering if someone could help me understand:
how, why and when I would use Protocols in my program in an intelligent way.

If you've done any kind of object-oriented programming, you probably know protocols as interfaces (they're not identical, but the concept is similar). If not, think of protocols as blueprints.
The main reason why you'd use protocols is so you can use objects without knowing everything about them; all you need to know is that they implement a set of methods. For example, if the classes Business and Person conform to the protocol Contact, which defines the method - (NSString *)phoneNumber, the class AddressBook can call -(NSString *)phoneNumber without knowing whether or not the object is of type Business or Person.
Once you start to learn about Cocoa and delegates, you'll see how powerful and important protocols are.

One word, delegates.
Objective-c uses delegates all over the place to allow classes to talk to each other.
To see an example see UITableViewDelegate Protocol
That's not the only place #protocol is used, but it's probably the most common use for it.

Protocols are better versions of callback functions in C.
Protocols are useful constructs when you want to implement MVC architecture yourself.
The Views need to be notified when Model changes,You can use protocols to notify appropriate events to Observers.

You could have a class that is a UIViewController, and it implements several protocols, such as UITableViewDelegate, UITableViewDataSource. A class can do more than one thing.

Like #conmulligan says Objective-C uses protocols to make classes talk to each other.
Its one of many ways to communicate between classes.
But protocols is necessarily a bad way.
I use protocols if I was to create a re-usable object, that is usually used for many projects.
So I create protocols to make my code easy to maintain.

Related

How to show relation between interfaces and classes in UML?

I have some related interfaces and classes that I want to represent in UML (sorry about the relationships, I don't know how to do it properly with StarUML):
The idea of an interface ISMS implementing IMessage and IStorable, instead of having directly the SMS class implementing itself both interfaces, aims to make the project more modular, maintainable, and easier to test.
Is this a good approach for the design? If so, is this a good way of representing them in an UML Class Diagram or is there a better way to represent an interface and its relationship with other interfaces/classes in UML?
I have a couple of remarks on top of Bruno's already very clear answer.
Your design
The decomposition of the interfaces into IStorable and IMessage seems at first sight to be a sound application of interface segregation principle.
Combining the two interfaces into a reusable ISMS interface instead of directly implementing them in a concrete SMS class will in this regard keep your code more maintainable, since it will easily allow to replace the SMS implementation with an alternative one (which makes sense if you consider that SMS functionality can be platform specific).
The question is however if SMS and email could not be used interchangeably. But only you can answer this question: If your design requires to keep those communication channels distinct (and maybe your real code adds some differences between the two interfaces), it's fine. But if not, it would make sense to allow such interchangeability and replace ISMS and IEmail with a single more general INotification.
Your UML representation
First of all, I'd like to reinforce Bruno's remark about the difference between generalization (plain line) and realization (dotted line).
Maybe I'm old school, but instead of using the circle for the interface, I'd advise for the more conventional interface as with a class box with the keyword «interface» above the name of the interface. Especially if you have properties and operations.
The circle is in my view better suitable for the lollipop notation of an interface. This is very practical when you have no much to say about the interface itself, but want to show what interfaces a class implements (lollipop) or is dependent on (socket). The interfaces details are then defined in another more detailed diagram. You can theoretically merge the two notations in the same diagram, but personally I find it less readable and would not advise it.
Is this a good approach for the design?
I think yes, also because MMS if you add it can also implement ISMS too (may renaming that interface).
For IEmail it is less clear except that simplify Email and other classes working with interfaces to have one interface rather than two
I am pretty sure Christophe will say much more about that :-)
is this a good way of representing them in an UML Class Diagram or is there a better way to represent an interface and its relationship with other interfaces/classes in UML?
the relation to indicate a class implements an interface is a realization (drawn with dotted line), you used a generalization, so also adding MMS :
... ISMS implementing IMessage and IStorable
warning this is not an implementation because ISMS is an interface, same for IEmail, this is why between interfaces the inheritance is supported by a generalization rather than a realization.

Is there a way to merge identical protocols between frameworks?

I'm working a project that has multiple components. Some of those components will need to be re-useable between apps -- the apps are related but cannot themselves be merged for business reasons. Thankfully the problem below isn't actually going to cause me issues, but I'm highly curious about how I'd solve it. Because someday I may just need to implement the following pattern.
So assuming I've got a CocoaPod named Foo and another named Bar. Foo reports to it's delegates using objects that implement the Foo.BussinessLogic protocol. Bar just happens to have an identical Bar.BussinessLogic protocol. I can write objects that conform to both protocols readily enough, but other than directly making Foo conform to Bar.BussinessLogic, how do I connect to the two without writing a pair of wrappers around each whose only job is to say item as! Bar.BussinessLogic when Foo sends a message to bar, and vice versa?
If the protocols share a bunch of methods, then my instinct would be to have them both conform to a common protocol in a third library that they both can depend on.
In Swift you can't just trick the compiler and say "trust me, they have the same methods".
However, I'm not sure if that answers your question since the types in your question are so nebulous. There are lots of other possible solutions. It depends on the situation.

iphone development: how can I inherit from more than one class? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Objective-C multiple inheritance
In my iPhone app I want to use googleAnalytics but the thing is I Have to inherit from GAITrackedViewController which is provided by Google. The problem is I already extend GLKViewController and objective-c does not allow multiple inheritance. some topics suggest to use protocols. I have no idea about them I have never used them before but I think it is too late because I already designed and implemented my project.What can I do? is there any example which solves that kind of a problem?
Objective C does not support multiple inheritance. But by using Composition, Protocols and Message Forwarding you will achieve the same result.
You should refer to apple doc for Multiple Inheritance and Message Forwarding on this link-AppleDoc
For Composition check this link
For Protocols in Objective C check this link Protocol in Objective C
Multiple inheritance is rarely a good idea.
implement multiple protocols. read Objective-C Introduction about protocols,
They are similar to java interfaces.
If that does not work, because these two classes would not provide a protocol, you still could use aggreation: Define two members, one for glkVieController, the other for gaiTrackedViewController

What's the difference between using an informal protocol on NSObject or an protocol with optional methods?

I'm studying some basics about informal protocols and real protocols. What confuses me is, that Cocoa seems to use a lot of informal protocols on NSObject. Those informal protocols are categories on NSObject which declare methods, but do not actually implement them.
As far as I get it right, the only reason they make use of informal protocols (in other words, categories on NSObject that don't provide method implementations), is to give an autocompletion-hint in Xcode.
One example is the -awakeFromNib method defined in NSNibLoading.h, which is an informal protocol on NSObject. The nib loading system checks at runtime if an object implements that method. If it does, then it calls it.
But now let's imagine there was no feature called informal protocol. The alternative that would have the exact same effect would have been a real #protocol declaration which declares an optional method -awakeFromNib. NSObject would just adopt that protocol and the compiler would happily provide autocompletion.
Can anyone point out the big difference between these two strategies? I don't see the point of informal protocols but would really like to do so.
Two huge differences:
Compile time type checking. An explicit protocol with optional methods is much more clear about what methods you could implement. Both for explicitly adorning the class with the protocol it conforms too, and Xcode can provide much more precise code-completion lists of what you could implement.
It keeps NSObject uncluttered. With the old style informal protocols all methods that are optional instead usually had their default implementation added to NSObject.
The informal protocols where a neat solution to a problem that no longer exist since the introduction of optional methods in protocols in Objective-C 2.0.
The big difference is that the #optional keyword was only introduced a few years ago. For new code, informal protocols are basically obsolete. Much of the frameworks is non-new code.
In order to use a protocol, you will have to import it, and let the object you are coding in conform to it
TestViewController : UIViewController <MyAwesomeProtocol>
In order for a category to be used, you do not have to do such things, you can simply import the category (which is not even required in all cases) and use the object (in my case a UIViewController) like you regularly would, and XCode would provide you with autocompletion for the category methods.
I prefer the protocol way, it is more strict and reliable. Categories tend to cause building issues and are a bit odd (in most, not all, cases) to be honest.

Objective-C: do you use #private visibility/access modifier in your code?

There are 3 modifiers: #private, #protected (default) and #public. Being accustomed to do so in C++ and other more sane languages, I always use #private for my fields. I barely (if ever)see that in SDK examples from Apple - they just rely on the default one.
One day I realized that Objective-C inheritance is rather fake feature: deriving an interface from another one doesn't mean all private fields are now available for redefinition. The compiler still sees them and disallows defining a new private field with the the same name, which goes orthogonal with classic encapsulation paradigm in OOD.
So I am a bit frustrated. Maybe I am expecting too much from the language because it's nothing more than a build up over standard C.
So do you use #private in your code? Why?
I guess it's a good idea to always use #private, but I've never bothered in the past because I generally use property accessors for almost all ivar access except in init and dealloc methods. So in practice, I rarely have a problem of accessing ivars by mistake.
Also, if you're targeting iOS 4+, you don't need to declare ivars for properties if you use #synthesize.
I should note that if you're writing library code that is meant to be subclassed by other developers, the use of #private would be more important.
I do out of habit, but it really doesn't matter unless you're shipping a binary framework others will link agianst, which I'm pretty sure you're not doing.
All #private does is restrict the visibility of the members of the object struct (accessed like obj->_ivar, rather than [obj getter] or obj.getter). It's a nice sanity check since it will error if you try to do it outside the class -- pretty much the only place to use direct structure access is when implementing NSCoding or NSCopying and those will still work -- but it doesn't really buy you much.
It's only really useful for Apple or folks who are shipping libraries that want to expose certain fields only to themselves in header files. We never use it because the accessor model lets you expose (or not) what you want. Since I have both header and source files what good is private really? Objective-C isn't C++ so #private has a different purpose.
In all the code I've written in Objective-C since 1989, I've never bothered to use #public, #protected, or #private.