Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are categories implemented in Objective C?

I know how to use categories as a programmer, but I'm curious how they are implemented. Does the compiler compile them into calls to class_replaceMethod from a static initializer? Thanks.

like image 725
Kartick Vaddadi Avatar asked Aug 11 '11 12:08

Kartick Vaddadi


People also ask

How does Objective-C categories work?

Categories provide the ability to add functionality to an object without subclassing or changing the actual object. A handy tool, they are often used to add methods to existing classes, such as NSString or your own custom objects.

How do you add a category in Objective-C?

Open your XCode project, click on File -> New -> File and choose Objective-C file , click Next enter your category name say "CustomFont" choose file type as Category and Class as UIFont then Click "Next" followed by "Create."

What is category in IOS?

A category allow you to add (only) methods to a class by declaring them in an interface file (. h) and defining them in an implementation file (. m), like in a basic Objective-C class. Sadly a category can't declare additional instance variable for a class.


1 Answers

New answer on topic.

Each class has a list of methods, when doing a method lookup the method list is scanned from beginning to end. If no method is found the superclass' list is scanned, etc. until reaching the root class. Found methods are cached for faster lookup next time.

When loading a category onto a class the categories method list is prepended to the existing list, and caches are flushed. Since the list is searched sequentially this means that the categories method will be found before the original method on next search.

This setup of categories is done lazily, from static data, when the class is first accessed. And can be re-done if loading a bundle with executable code.

In short it is a bit more low level than class_replaceMethod().

like image 67
PeyloW Avatar answered Oct 18 '22 13:10

PeyloW