Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protocol versus Category

Can anyone explain the differences between Protocols and Categories in Objective-C? When do you use one over the other?

like image 289
Coocoo4Cocoa Avatar asked Dec 11 '08 21:12

Coocoo4Cocoa


People also ask

What is the difference between protocol and class?

You can create objects from classes, whereas protocols are just type definitions. Try to think of protocols as being abstract definitions, whereas classes and structs are real things you can create.

What is the difference between category VS extension?

Category and extension both are basically made to handle large code base, but category is a way to extend class API in multiple source files while extension is a way to add required methods outside the main interface file.

What is the difference between an extension and a protocol extension?

Protocols let you describe what methods something should have, but don't provide the code inside. Extensions let you provide the code inside your methods, but only affect one data type – you can't add the method to lots of types at the same time.

What is difference between Objective C protocol and Swift 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.


1 Answers

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.

like image 158
mipadi Avatar answered Sep 28 '22 05:09

mipadi