thebushidocollective/han/objc-protocols-categories

Claude Code and agent skill by thebushidocollective/han

Trust tier 2
  • community
Source check pending

Checking that the SKILL.md file is still in the repository.

Use when objective-C protocols for defining interfaces and categories for extending classes, including formal protocols, optional methods, class extensions, and patterns for modular, reusable code design.

Install

npx vskill@latest install thebushidocollective/han/objc-protocols-categories

SKILL.md

Objective-C Protocols and Categories

Introduction

Protocols and categories are fundamental Objective-C features for defining interfaces and extending behavior. Protocols declare method contracts that classes can adopt, enabling polymorphism and delegation patterns. Categories extend existing classes with new methods without subclassing or source access.

Protocols serve similar purposes to Java interfaces or Swift protocols, enabling multiple inheritance of behavior through composition. Categories are unique to Objective-C, allowing developers to organize code, add functionality to system classes, and split large implementations across multiple files.

This skill covers formal protocols, optional methods, protocol composition, categories, class extensions, and best practices for modular Objective-C design.

Formal Protocols

Formal protocols declare method and property requirements that adopting classes must implement, establishing contracts for polymorphic behavior.

objectivec
// Basic protocol declaration
@protocol Drawable <NSObject>
@required
- (void)draw;
- (CGRect)bounds;
@optional
- (void)drawWithStyle:(NSString *)style;
@end
// Protocol adoption in interface
@interface Circle : NSObject <Drawable>
@property (nonatomic, assign) CGFloat radius;
@property (nonatomic, assign) CGPoint center;
@end
@implementation Circle
- (void)draw {
NSLog(@"Drawing circle at (%.1f, %.1f) with radius %.1f",
self.center.x, self.center.y, self.radius);
}
- (CGRect)bounds {
return CGRectMake(
self.center.x - self.radius,
self.center.y - self.radius,
self.radius * 2,
self.radius * 2
);
}
@end
// Multiple protocol adoption
@protocol Movable <NSObject>
- (void)moveToPoint:(CGPoint)point;
- (CGPoint)currentPosition;
@end
@protocol Scalable <NSObject>
- (void)scaleBy:(CGFloat)factor;
- (CGFloat)currentScale;
@end
@interface Shape : NSObject <Drawable, Movable, Scalable>
@property (nonatomic, assign) CGPoint position;
@property (nonatomic, assign) CGFloat scale;
@end
@implementation Shape
- (void)draw {
NSLog(@"Drawing shape");
}
- (CGRect)bounds {
return CGRectZero;
}
- (void)moveToPoint:(CGPoint)point {
self.position = point;
}
- (CGPoint)currentPosition {
return self.position;
}
- (void)scaleBy:(CGFloat)factor {
self.scale *= factor;
}
- (CGFloat)currentScale {
return self.scale;
}
@end
// Protocol as type
void drawShapes(NSArray<id<Drawable>> *shapes) {
for (id<Drawable> shape in shapes) {
[shape draw];
NSLog(@"Bounds: %@", NSStringFromCGRect([shape bounds]));
}
}
// Checking protocol conformance
void checkConformance(id object) {
if ([object conformsToProtocol:@protocol(Drawable)]) {
id<Drawable> drawable = object;
[drawable draw];
}
}
// Protocol inheritance
@protocol AdvancedDrawable <Drawable>
- (void)drawWithTransform:(CGAffineTransform)transform;
- (void)drawWithBlendMode:(CGBlendMode)blendMode;
@end
@interface AdvancedShape : NSObject <AdvancedDrawable>
@end
@implementation AdvancedShape
- (void)draw {
NSLog(@"Advanced drawing");
}
- (CGRect)bounds {
return CGRectZero;
}
- (void)drawWithTransform:(CGAffineTransform)transform {
NSLog(@"Drawing with transform");
}
- (void)drawWithBlendMode:(CGBlendMode)blendMode {
NSLog(@"Drawing with blend mode");
}
@end

Protocols enable polymorphic code that works with any object implementing the required methods, regardless of class hierarchy.

Optional Protocol Methods

Optional protocol methods allow adopters to implement only relevant methods, with runtime checking for implementation before calling.

objectivec
// Protocol with optional methods
@protocol DataSourceDelegate <NSObject>
@required
- (NSInteger)numberOfItems;
@optional
- (NSString *)titleForItemAtIndex:(NSInteger)index;
- (UIImage *)imageForItemAtIndex:(NSInteger)index;
- (void)didSelectItemAtIndex:(NSInteger)index;
@end
// Implementing partial optional methods
@interface ListView : UIView <DataSourceDelegate>
@property (nonatomic, weak) id<DataSourceDelegate> dataSource;
@end
@implementation ListView
- (void)reloadData {
NSInteger count = [self.dataSource numberOfItems];
for (NSInteger i = 0; i < count; i++) {
// Check if optional method is implemented
if ([self.dataSource respondsToSelector:
@selector(titleForItemAtIndex:)]) {
NSString *title = [self.dataSource titleForItemAtIndex:i];
NSLog(@"Title: %@", title);
}
if ([self.dataSource respondsToSelector:
@selector(imageForItemAtIndex:)]) {
UIImage *image = [self.dataSource imageForItemAtIndex:i];
NSLog(@"Image: %@", image);
}
}
}
// Required method implementation
- (NSInteger)numberOfItems {
return 0;
}
@end
// Selective implementation in adopter
@interface SimpleDataSource : NSObject <DataSourceDelegate>
@end
@implementation SimpleDataSource
- (NSInteger)numberOfItems {
return 10;
}
- (NSString *)titleForItemAtIndex:(NSInteger)index {
return [NSString stringWithFormat:@"Item %ld", (long)index];
}
// imageForItemAtIndex: not implemented
@end
// Delegate pattern with optional methods
@protocol ViewControllerDelegate <NSObject>
@optional
- (void)viewControllerWillAppear:(UIViewController *)controller;
- (void)viewControllerDidAppear:(UIViewController *)controller;
- (void)viewControllerWillDisappear:(UIViewController *)controller;
- (void)viewControllerDidDisappear:(UIViewController *)controller;
@end
@interface CustomViewController : UIViewController
@property (nonatomic, weak) id<ViewControllerDelegate> delegate;
@end
@implementation CustomViewController
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
if ([self.delegate respondsToSelector:
@selector(viewControllerWillAppear:)]) {
[self.delegate viewControllerWillAppear:self];
}
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
if ([self.delegate respondsToSelector:@selector(viewControllerDidAppear:)]) {
[self.delegate viewControllerDidAppear:self];
}
}
@end
// Property requirements in protocols
@protocol Identifiable <NSObject>
@required
@property (nonatomic, readonly) NSString *identifier;
@property (nonatomic, strong) NSString *name;
@optional
@property (nonatomic, strong) NSDictionary *metadata;
@end
@interface User : NSObject <Identifiable>
@end
@implementation User
@synthesize identifier = _identifier;
@synthesize name = _name;
// metadata not implemented (optional)
@end

Always check for optional method implementation with respondsToSelector: before calling to prevent crashes from unimplemented methods.

Categories for Class Extension

Categories add methods to existing classes without subclassing, enabling code organization and extension of system classes.

objectivec
// Basic category
@interface NSString (Validation)
- (BOOL)isValidEmail;
- (BOOL)isValidPhoneNumber;
- (NSString *)trimmedString;
@end
@implementation NSString (Validation)
- (BOOL)isValidEmail {
NSString *emailRegex =
@"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}";
NSPredicate *predicate = [NSPredicate predicateWithFormat:
@"SELF MATCHES %@", emailRegex];
return [predicate evaluateWithObject:self];
}
- (BOOL)isValidPhoneNumber {
NSString *phoneRegex = @"^\\d{3}-\\d{3}-\\d{4}$";
NSPredicate *predicate = [NSPredicate predicateWithFormat:
@"SELF MATCHES %@", phoneRegex];
return [predicate evaluateWithObject:self];
}
- (NSString *)trimmedString {
return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
@end
// Using category methods
void categoryExample(void) {
NSString *email = @"user@example.com";
if ([email isValidEmail]) {
NSLog(@"Valid email");
}
NSString *text = @" Hello World ";
NSString *trimmed = [text trimmedString];
NSLog(@"Trimmed: '%@'", trimmed);
}
// Category for code organization
@interface DataManager : NSObject
- (void)saveData:(NSData *)data;
- (NSData *)loadData;
@end
// Split functionality across categories
@interface DataManager (NetworkSync)
- (void)syncToServer;
- (void)downloadFromServer;
@end
@interface DataManager (LocalStorage)
- (void)saveToUserDefaults:(NSDictionary *)data;
- (NSDictionary *)loadFromUserDefaults;
@end
@implementation DataManager
- (void)saveData:(NSData *)data {
NSLog(@"Saving data");
}
- (NSData *)loadData {
return [NSData data];
}
@end
@implementation DataManager (NetworkSync)
- (void)syncToServer {
NSLog(@"Syncing to server");
}
- (void)downloadFromServer {
NSLog(@"Downloading from server");
}
@end
@implementation DataManager (LocalStorage)
- (void)saveToUserDefaults:(NSDictionary *)data {
[[NSUserDefaults standardUserDefaults] setObject:data forKey:@"data"];
}
- (NSDictionary *)loadFromUserDefaults {
return [[NSUserDefaults standardUserDefaults] dictionaryForKey:@"data"];
}
@end
// Category on UIKit classes
@interface UIColor (CustomColors)
+ (UIColor *)brandPrimaryColor;
+ (UIColor *)brandSecondaryColor;
@end
@implementation UIColor (CustomColors)
+ (UIColor *)brandPrimaryColor {
return [UIColor colorWithRed:0.2 green:0.4 blue:0.8 alpha:1.0];
}
+ (UIColor *)brandSecondaryColor {
return [UIColor colorWithRed:0.8 green:0.4 blue:0.2 alpha:1.0];
}
@end
// Using custom colors
void customColorExample(void) {
UIView *view = [[UIView alloc] init];
view.backgroundColor = [UIColor brandPrimaryColor];
}
// Category with associated objects
#import <objc/runtime.h>
@interface UIViewController (CustomProperty)
@property (nonatomic, strong) NSString *customIdentifier;
@end
@implementation UIViewController (CustomProperty)
- (NSString *)customIdentifier {
return objc_getAssociatedObject(self, @selector(customIdentifier));
}
- (void)setCustomIdentifier:(NSString *)customIdentifier {
objc_setAssociatedObject(
self,
@selector(customIdentifier),
customIdentifier,
OBJC_ASSOCIATION_RETAIN_NONATOMIC
);
}
@end

Categories cannot add instance variables but can add methods and use associated objects for property-like behavior.

Class Extensions

Class extensions are anonymous categories declared in implementation files that can add private methods and properties invisible to clients.

objectivec
// Public interface
@interface Person : NSObject
@property (nonatomic, strong, readonly) NSString *name;
@property (nonatomic, assign, readonly) NSInteger age;
- (instancetype)initWithName:(NSString *)name age:(NSInteger)age;
- (NSString *)description;
@end
// Class extension (private interface)
@interface Person ()
// Make readonly properties readwrite internally
@property (nonatomic, strong, readwrite) NSString *name;
@property (nonatomic, assign, readwrite) NSInteger age;
// Private properties
@property (nonatomic, strong) NSString *internalID;
@property (nonatomic, strong) NSMutableArray *privateData;
// Private methods
- (void)validateData;
- (void)logAccess;
@end
@implementation Person
- (instancetype)initWithName:(NSString *)name age:(NSInteger)age {
self = [super init];
if (self) {
self.name = name;
self.age = age;
self.internalID = [[NSUUID UUID] UUIDString];
self.privateData = [NSMutableArray array];
[self validateData];
}
return self;
}
- (NSString *)description {
[self logAccess];
return [NSString stringWithFormat:@"%@ (%ld)", self.name, (long)self.age];
}
// Private method implementations
- (void)validateData {
NSAssert(self.name.length > 0, @"Name must not be empty");
NSAssert(self.age >= 0, @"Age must be non-negative");
}
- (void)logAccess {
NSLog(@"Accessed person: %@", self.internalID);
}
@end

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 100 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
198
Repository forks
21
7-day trend score
26

Stars and forks are for the whole GitHub repository, not this skill alone. Refreshed 18 Mar 2026, 7 months ago.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/thebushidocollective/han/objc-protocols-categories/badge)](https://verified-skill.com/skills/thebushidocollective/han/objc-protocols-categories)

Something wrong with this skill or its page? Tell us.