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.
Let's create a category that add functionality to UIFont class. 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."
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.
In Objective C they were called categories, but in Swift they are called extensions. The purpose of both of them are to give additional functionality to existing classes without having to create subclasses.
A class can be extended in Objective C using a category such as:
@interface NSString (CategoryName)
-(NSString *)myFabulousAddition; // a fabulous additional method
@end
/////////////////////////////
@implementation NSString (CategoryName)
-(NSString *)myFabulousAddition {
// do something fabulous...
}
@end
In this small example, I would be adding the method myFabulousAddition
to NSString. I could then call it by [anNSString myFabulousAddition]
just as if it were part of the NSString set of methods. Great and useful.
In the Apple documents regarding Categories, the docs state:
There’s no limit to the number of categories that you can add to a class, but each category name must be different, and each should declare and define a different set of methods.
What if you have something like this:
@interface NSString (CategoryName)
-(NSString *)myFabulousAddition; // a fabulous additional method
@end
@interface NSString (ANOTHERCategoryName)
-(NSString *)myFabulousAddition; // a DIFFERENT fabulous additional method
// BUT with same name as the other category
@end
/////////////////////////////
@implementation NSString (CategoryName)
-(NSString *)myFabulousAddition {
// do something fabulous...
}
@end
@implementation NSString (ANOTHERCategoryName)
-(NSString *)myFabulousAddition {
// do something equally fabulous, but DIFFERENT...
}
@end
The lack of a name in the parenthesis indicates that the form is an extension to the class, like so:
@interface MyObject () // No name -- an extension vs category to MyObject
- (void)setNumber:(NSNumber *)newNumber;
@end
Does the category name have any meaning to the compiler or linker? Is the category name part of the method signature in anyway or is it part of a primitive namespace? If the category name is meaningless, how do you know if you are about to stomp on another method and get undefined behavior?
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