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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With