Objective-C Protocols and Categories
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.
What this skill does
# 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 = @"[email protected]";
if ([email isValidEmail]) {
NSLog(@"Valid email");
}
NSString *text = @" Hello World ";
NSStringRelated in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.