First I designed a protocol as my base class, which could not be instantiated. Later I found there should be some shared methods between classes conformed to this protocol, so I'd like to add some default implementation to the protocol.
AFAIK, Obj-C doesn't support protocol with default behaviors so I have to make it an interface. Then came up with my question, how to make an interface cannot be instantiated?
Thanks.
Interfaces can't be instantiated, ever. Maybe you're thinking about abstract classes, which aren't really available in Objective-C. Maybe you should rethink your program structure and try to use more inheritance. If the class you are inheriting from conforms to a certain protocol ( which is somewhat of the Objective-C equivalent of Java Interfaces ), then you can instantiate that, or subclass it and then instantiate it.
Have a look here for more information about inheritance: http://www.techotopia.com/index.php/Objective-C_Inheritance
Related
From Apple's own website: "At the heart of Swift's design are two incredibly powerful ideas: protocol-oriented programming and first class value semantics."
Can someone please elaborate what exactly is protocol oriented programming, and what added value does it bring?
I have read this and watched the Protocol-Oriented Programming in Swift video, but coming from an Objective-C background still haven't understood it. I kindly ask for a very plain English answer along with code snippets & technical details about how it's different from Objective-C.
Just one of the confusions I have is using <tableViewDelegate, CustomDelegate> Couldn't we also conform to multiple protocols in Objective-C as well? So again how is Swift new?
EDIT: See Protocol-Oriented Views video. I find this video to be more basic and easier to grasp a meaningful use case. The WWDC video itself is a bit advanced and requires more breadth. Additionally the answers here are somewhat abstract.
Preface: POP and OOP are not mutually exclusive. They're design paradigms that are greatly related.
The primary aspect of POP over OOP is that is prefers composition over inheritance. There are several benefits to this.
In large inheritance hierarchies, the ancestor classes tend to contain most of the (generalized) functionality, with the leaf subclasses making only minimal contributions. The issue here is that the ancestor classes end up doing a lot of things. For example, a Car drives, stores cargo, seats passengers, plays music, etc. These are many functionalities that are each quite distinct, but they all get indivisibly lumped into the Car class. Descendants of Car, such as Ferrari, Toyota, BMW, etc. all make minimal modifications to this base class.
The consequence of this is that there is reduced code reuse. My BoomBox also plays music, but it's not a car. Inheriting the music-playing functionality from Car isn't possible.
What Swift encourages instead is that these large monolithic classes be broken down into a composition of smaller components. These components can then be more easily reused. Both Car and BoomBox can use MusicPlayer.
Swift offers multiple features to achieve this, but the most important by far are protocol extensions. They allow implementation of a protocol to exist separate of its implementing class, so that many classes may simply implement this protocol and instantly gain its functionality.
It surprised me that none of the answers mentioned value type in POP.
To understand what is protocol oriented programming, you need to understand what are drawbacks of objected oriented programming.
It (Objc) has only one inheritance. If we have very complicated hierarchy of inheritance, the bottom class may have a lot of unnecessary state to hold.
It uses class which is a reference type. Reference type may cause code unsafe. e.g. Processing collection of reference types while they are being modified.
While in protocol oriented programming in swift:
It can conform multiple protocols.
It can be used by not only class, but also structures and enumerations.
It has protocol extension which gives us common functionality to all types that conforms to a protocol.
It prefers to use value type instead of reference type. Have a look at the standard swift library here, you can find majority of types are structures which is value type. But this doesn't mean you don't use class at all, in some situation, you have to use class.
So protocol oriented programming is nothing but just an another programming paradigm that try to solve the OOP drawbacks.
In Objective C protocol is the same thing as interface in most languages. So in Objective C protocol's usage is limited to SOLID principle "Depend upon Abstractions. Do not depend upon concretions."
In Swift protocols were improved so seriously that since they still could be used as interfaces in fact they are closer to classes (like Abstract classes in C++)
In Objective C the only way to share functionality between classes is an inheritance. And you could inherit the only one parent class. In Swift you could also adopt as many protocols as you want. And since protocols in Swift can have default methods implementation they give us a fully-functional Multiple inheritance. More flexibility, better code reuse - awesome!
Conclusion:
Protocol Oriented Programming is mostly the same as OOP but it pays additional attention to functionality sharing not only via inheritance but also via protocol adoption (Composition over inheritance).
Worth to mention that in C++ abstract classes are very similar to protocols in Swift but no one says C++ supports some specific type of OOP. So in general POP is a one of the versions of OOP if we speak about programming paradigms. For Swift POP is an improved version of OOP.
Adding to the above answer
Protocol is a interface in which signature of methods and properties are declared and any class/struct/enum subclassing the enum must have to obey the contract means they have to implement all the methods and properties declared in superclass protocol.
Reason to use Protocol
Classes provide single inheritance and struct doesn't support inheritance. Thus protocols was introduced.
Extension The methods declare inside the protocol can be implemented inside the extension to avoid the redundancy of the code in case protocol is being inherited in multiple class / struct having same method implementation. We can call the method by simply declaring the object of struct/enums. Even we can restrict the extension to a list of classes, only restricted class will be able to use the method implemented inside the extension while rest of the classes have to implement method inside own class.
Example
protocol validator{
var id : String{ get }
func capitialise()-> (String)
}
extension validator where Self : test{
func capitialise() -> String{
return id.capitalized
}
}
class test : validator {
var id: String
init(name:String) {
id = name
}
}
let t = test(name: "Ankit")
t.capitialise()
When to use In OOP suppose we have a vehicle base class which is inherited by the airplane, bike, car etc. Here break, acceleration may be common method among three subclass but not the flyable method of airplane. Thus if we are declaring flyable method also in OOP, the bike and car subclass also have the inherit flyable method which is of no use for those class. Thus in the POP we can declare two protocols one is for flyable objects and other is for break and acceleration methods. And flyable protocol can be restricted to use by only the airplane
Protocol Oriented Programming(POP)
protocol-first approach
Protocol as a key point of OOP concept. abstraction, inheritance, polymorphism, encapsulation.
Protocol as a base for SOLID[About]
Protocol instead of class hierarchy tree. Its is hard to support class inheritance. Moreover it has some performance impact
Class/struct can implements multiple protocols(a kind of multiple inheritance)
Composition over inheritance.
extension MyClass: MyProtocol {
}
Default method. Shared implementation for all implementators
extension MyProtocol {
func foo() {
//logic
}
}
Protocol inheritance. One protocol can extends another protocol. Implementator of protocol one should implements all from first and the second protocols
protocol ProtocolB: ProtocolA {
}
value type implement protocol(as usual reference type)[About]
Protocol Oriented Programming (POP)
Came since Swift 2.0
class (OOP)
is reference type
memory leak, incorrect data stored,race condition to access in complex multi-thread environments
can be large by inheriting members of super classes at chain time
struct (POP)
is value type - each time a fresh copy is made when needed
provides multi inheritance - inherits protocols
Protocol :
Defines what Methods, Properties and Initializes are required o Can
inherit another Protocol(s)
Don’t have to use override keyword to implement protocol functions
Extensions:
Default value and
The default implementation for protocol
Can add extra members to
protocol
what is protocol oriented programming? What’s POP?
is a new programming paradigm
we start designing our system by defining protocols. We rely on new concepts: protocol extensions, protocol inheritance, and protocol compositions.
value types can inherit from protocols, even multiple protocols. Thus, with POP, value types have become first class citizens in Swift. value types like enums, structs
*POP lets you to add abilities to a class or struct or enum with protocols which supports multiple implementations.
Apple tells us:
“Don’t start with a class, start with a protocol.”
Why? Protocols serve as better abstractions than classes.
Protocols: are a fundamental feature of Swift. They play a leading role in the structure of the Swift standard library and are a common method of abstraction.
Protocols are used to define a “blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality.”
Benefits of Protocol-Oriented Programming:
All classes are decoupled from each other
Separating the concerns of declaration from implementation
Reusability
Testability
I have found that we can create model classes in Objective-C using following methods.
Create a protocol with some properties and methods. Implementing this protocol in any of the classes provide us an inheritance feature of OOP concept.
Create a NSObject class with interface and implementation. Add properties and method declarations to that class. SubClassing of this class also provide us an inheritance feature of OOP concept.
First of all I have to know that, these two methods will work as it stated.
If it will work what is difference between them, pros and cons.
Thanks in Advance.
What are those major pro and contra for #protocol and Class Clusters concepts in Objective-C ?
Both of them introduce Loose Coupling in program architecture. Are they conceptually almost equal, or is there something else worth to know ?
Caveat: Not a cocoa pro, but I don't believe they are equal at all.
With Class Clusters you subclass.
Class clusters are a design pattern that the Foundation framework makes extensive use of. Class clusters group a number of private concrete subclasses under a public abstract superclass. The grouping of classes in this way simplifies the publicly visible architecture of an object-oriented framework without reducing its functional richness. Class clusters are based on the Abstract Factory design pattern discussed in “Cocoa Design Patterns.”
#protocols on the other hand, are more like Java interfaces.
The Objective-C extension called a protocol is very much like an interface in Java. Both are simply a list of method declarations publishing an interface that any class can choose to implement. The methods in the protocol are invoked by messages sent by an instance of some other class.
In short, Class Clusters are subclass/superclass where the subclass conforms to the entire identity of the superclass so that the implementation can be hidden from the user. This is apparent in the case of NSArray where the compiler uses context to choose the best type of data structure to use. You don't call NSTree or NSLinkedList like you might in Java. You can see how NSNumber is implemented here, especially the part where it says:
// NSNumber instance methods -- which will never be called...
#protocols are like client/server relationship where the client class adopts a protocol of the server class, so the server can call functionality on the client. <NSAppDelegate> and <UIAlertViewDelegate> are great examples of the use of protocols.
This is the situation. I've been a C++ programmer for ages. I like abstract classes and "interfaces" so I would likt to do the same using objc.
I use a protocol for my interfaces, but the problem is that when my abstract class inherits from the protocol (I don't want to implement it here) I get warnings like:
warning: method definition for 'XXXXX' not found and 'XXXXX' class does not fully implement the 'XXXXXX' protocol.
Is there anyway to supress this? I hope child classes of this ones will throw "correct warnings" if base class did not implemented the protocol.
Another option is to inherit from the protocol just when needed, but I like to force this in the base class to make sure inherited implementes the interface.
Any tip?,
Thanks in advance.
When you implement a protocol in an Objective-C class, you have to implement all the methods. However, you can provide stub implementations. This mailing list post describes how to use doesNotRecognizeSelector: in "abstract" classes.
I don't think there is a solution in a way you are looking for. You must define all methods declared in the protocol, at least implement them as an empty methods.
I understand that you are looking for a C++ like code, but Obj-C is different and we must live with it. Also, gcc supports c++/obj-c mix, so you can write some part of the project in pure C++ what is great when you need some low-level code or want something easy to port.
Can anyone explain the differences between Protocols and Categories in Objective-C? When do you use one over the other?
A protocol is the same thing as an interface in Java: it's essentially a contract that says, "Any class that implements this protocol will also implement these methods."
A category, on the other hand, just binds methods to a class. For example, in Cocoa, I can create a category for NSObject that will allow me to add methods to the NSObject class (and, of course, all subclasses), even though I don't really have access to NSObject.
To summarize: a protocol specifies what methods a class will implement; a category adds methods to an existing class.
The proper use of each, then, should be clear: Use protocols to declare a set of methods that a class must implement, and use categories to add methods to an existing class.
A protocol says, "here are some methods I'd like you to implement." A category says, "I'm extending the functionality of this class with these additional methods."
Now, I suspect your confusion stems from Apple's use of the phrase "informal protocol". Here's the key (and most confusing) point: an informal protocol is actually not a protocol at all. It's actually a category on NSObject. Cocoa uses informal protocols pervasively to provide interfaces for delegates. Since the #protocol syntax didn't allow optional methods until Objective-C 2.0, Apple implemented optional methods to do nothing (or return a dummy value) and required methods to throw an exception. There was no way to enforce this through the compiler.
Now, with Objective-C 2.0, the #protocol syntax supports the #optional keyword, marking some methods in a protocol as optional. Thus, your class conforms to a protocol so long as it implements all the methods marked as #required. The compiler can determine whether your class implements all the required methods, too, which is a huge time saver. The iPhone SDK exclusively uses the Objective-C 2.0 #protocol syntax, and I can't think of a good reason not to use it in any new development (except for Mac OS X Cocoa apps that need to run on earlier versions of Mac OS X).
Categories:
A category is a way of adding new methods to all instances of an existing class without modifying the class itself.
You use a category when you want to add functionality to an existing class without deriving from that class or re-writing the original class.
Let's say you are using NSView objects in cocoa, and you find yourself wishing that all instances of NSView were able to perform some action. Obviously, you can't rewrite the NSView class, and even if you derive from it, not all of the NSView objects in your program will be of your derived type. The solution is to create a category on NSView, which you then use in your program. As long as you #import the header file containing your category declaration, it will appear as though every NSView object responds to the methods you defined in the catagory source file.
Protocols:
A protocol is a collection of methods that any class can choose to implement.
You use a protocol when you want to provide a guarantee that a certain class will respond to a specific set of methods. When a class adopts a protocol, it promises to implement all of the methods declared in the protocol header. This means that any other classes which use that class can be certain that those methods will be implemented, without needing to know anyting else about the class.
This can be useful when creating a family of similar classes that all need to communicate with a common "controller" class. The communication between the controller class and the controlled classes can all be packaged into a single protocol.
Side note: the objective-c language does not support multiple inheritance (a class can only derive from one superclass), but much of the same functionality can be provided by protocols because a class can conform to several different protocols.
To my understanding Protocols are a bit like Java's Interfaces. Protocols declare methods , but the implementation is up to each class. Categories seems to be something like Ruby's mixins. With Categories you can add methods to existing classes. Even built-in classes.
A protocol allows you to declare a list of methods which are not confined to any particular class or categories. The methods declared in the protocol can be adopted any class/categories. A class or category which adopts a protocol must implements all the required methods declared in the protocol.
A category allows you to add additional methods to an existing class but they do not allow additional instance variables. The methods the category adds become part of the class type.
Protocols are contracts to implement the specified methods. Any object that conforms to a protocol agrees to provide implementations for those methods. A good use of a protocol would be to define a set of callback methods for a delegate (where the delegate must respond to all methods).
Categories provide the ability to extend a current object by adding methods to it (class or instance methods). A good use for a category would be extending the NSString class to add functionality that wasn't there before, such as adding a method to create a new string that converts the receiver into 1337 5P34K.
NSString *test = #"Leet speak";
NSString *leet = [test stringByConvertingToLeet];
Definitions from S.G.Kochan's "Programming in Objective-C":
Categories:
A category provides an easy way for you to modularize the definition of a class into groups or categories of related methods. It also gives you an easy way to extend an existing class definition without even having access to the original source code for the class and without having to create a subclass.
Protocols:
A protocol is a list of methods that is shared among classes. The methods listed in the protocol do not have corresponding implementations; they’re meant to be implemented by someone else (like you!). A protocol provides a way to define a set of methods that are somehow related with a specified name. The methods are typically documented so that you know how they are to perform and so that you can implement them in your own class definitions, if desired.
A protocol list a set of methods, some of which you can optionally implement, and others that you are required to implement. If you decide to implement all of the required methods for a particular protocol, you are said to conform to or adopt that protocol. You are allowed to define a protocol where all methods are optional, or one where all are required.