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.
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.
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."
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.
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()
.
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