Objective-C Language Categories Create a Category on XCode

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Categories provide the ability to add some extra functionality to an object without subclassing or changing the actual object.

For example we want to set some custom fonts. 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."

enter image description here

enter image description here

Declare the Category Method :-

Click "UIFont+CustomFonts.h" to view the new category's header file. Add the following code to the interface to declare the method.

@interface UIFont (CustomFonts)

+(UIFont *)productSansRegularFontWithSize:(CGFloat)size;

@end

Now Implement the Category Method:-

Click "UIFont+CustomFonts.m" to view the category's implementation file. Add the following code to create a method that will set ProductSansRegular Font.

+(UIFont *)productSansRegularFontWithSize:(CGFloat)size{
    
    return [UIFont fontWithName:@"ProductSans-Regular" size:size];
    
}

Import your category

#import "UIFont+CustomFonts.h"

Now set the Label font

[self.label setFont:[UIFont productSansRegularFontWithSize:16.0]];


Got any Objective-C Language Question?