Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class extension vs class category

Class extensions @interface Class () are a lot more powerful and can inject variables into the class. Categories @interface Class (Category) can't.

What other differences are there, and when should one use a category over a class extension?

like image 655
AWF4vk Avatar asked Aug 21 '11 03:08

AWF4vk


People also ask

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 category in IOS?

You use categories to define additional methods of an existing class—even one whose source code is unavailable to you—without subclassing. You typically use a category to add methods to an existing class, such as one defined in the Cocoa frameworks.

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.

How do you extend a class in Objective-C?

The methods declared by a class extension are implemented in the implementation block for the original class, so you can't, for example, declare a class extension on a framework class, such as a Cocoa or Cocoa Touch class like NSString. Extensions are actually categories without the category name.


1 Answers

The main difference is that with an extension, the compiler will expect you to implement the methods within your main @implementation, whereas with a category you have a separate @implementation block. So you should pretty much only use an extension at the top of your main .m file (the only place you should care about ivars, incidentally) -- it's meant to be just that, an extension.

like image 52
jtbandes Avatar answered Nov 10 '22 01:11

jtbandes