Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

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…

TheBushidoCollectiveот TheBushidoCollective★ 202 звезды на GitHub

Об этом скилле

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.

// 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.

// 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 SimpleDataSou
Полный SKILL.md на GitHub

Установить Objective-C Protocols and Categories в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл 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.

Как установить скилл Objective-C Protocols and Categories?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл Objective-C Protocols and Categories запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить Objective-C Protocols and Categories с