Objective-C Blocks and GCD
БесплатноБез исполняемых скриптовНе проверенUse when blocks (closures) and Grand Central Dispatch in Objective-C for concurrent programming including block syntax, capture semantics, dispatch queues…
от TheBushidoCollective★ 202 звезды на GitHubОб этом скилле
Objective-C Blocks and GCD
Introduction
Blocks are Objective-C's closure implementation, providing anonymous functions that capture surrounding context. Grand Central Dispatch (GCD) is Apple's low-level API for managing concurrent operations using dispatch queues rather than threads directly.
Blocks enable functional programming patterns, callbacks, and clean asynchronous API design. GCD simplifies concurrency by abstracting thread management into queues that automatically distribute work across available CPU cores. Together, they form the foundation for modern Objective-C concurrent programming.
This skill covers block syntax and semantics, capture behavior, GCD queues and dispatch functions, synchronization primitives, and patterns for safe concurrent code.
Block Syntax and Usage
Blocks are first-class objects that encapsulate code and can capture variables from their defining scope.
// Basic block syntax
void (^simpleBlock)(void) = ^{
NSLog(@"Hello from block");
};
simpleBlock(); // Call block
// Block with parameters
int (^addBlock)(int, int) = ^(int a, int b) {
return a + b;
};
int result = addBlock(5, 3); // 8
// Block with return type
NSString *(^greetBlock)(NSString *) = ^NSString *(NSString *name) {
return [NSString stringWithFormat:@"Hello, %@", name];
};
NSString *greeting = greetBlock(@"Alice");
// Blocks as method parameters
- (void)fetchDataWithCompletion:
(void (^)(NSData *data, NSError *error))completion {
dispatch_async(dispatch_get_global_queue(
DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Simulate network call
NSData *data = [@"response" dataUsingEncoding:NSUTF8StringEncoding];
dispatch_async(dispatch_get_main_queue(), ^{
if (completion) {
completion(data, nil);
}
});
});
}
// Using block-based API
- (void)loadData {
[self fetchDataWithCompletion:^(NSData *data, NSError *error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"Data: %@", data);
}
}];
}
// Typedef for block types
typedef void (^CompletionBlock)(BOOL success);
typedef void (^DataBlock)(NSData *data, NSError *error);
typedef NSString *(^TransformBlock)(NSString *input);
- (void)performOperationWithCompletion:(CompletionBlock)completion {
// Async operation
dispatch_async(dispatch_get_global_queue(
DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Work
BOOL success = YES;
dispatch_async(dispatch_get_main_queue(), ^{
if (completion) {
completion(success);
}
});
});
}
// Blocks in collections
NSArray *blocks = @[
^{ NSLog(@"Block 1"); },
^{ NSLog(@"Block 2"); },
^{ NSLog(@"Block 3"); }
];
for (void (^block)(void) in blocks) {
block();
}
// Block properties
@interface AsyncOperation : NSObject
@property (nonatomic, copy) CompletionBlock completion;
@property (nonatomic, copy) DataBlock dataHandler;
@end
@implementation AsyncOperation
@end
Blocks must be copied when stored in properties or collections to move them from stack to heap storage.
Block Capture Semantics
Blocks capture variables from their defining scope, with different behaviors for different storage types and qualifiers.
// Capturing local variables
void captureExample(void) {
NSInteger x = 10;
void (^block)(void) = ^{
NSLog(@"x = %ld", (long)x); // Captures value of x
};
x = 20;
block(); // Prints "x = 10" (captured at block creation)
}
// __block qualifier for mutable capture
void mutableCaptureExample(void) {
__block NSInteger counter = 0;
void (^incrementBlock)(void) = ^{
counter++; // Can modify counter
};
incrementBlock();
incrementBlock();
NSLog(@"Counter: %ld", (long)counter); // 2
}
// Capturing self in methods
@interface Counter : NSObject
@property (nonatomic, assign) NSInteger count;
- (void)incrementAsync;
@end
@implementation Counter
- (void)incrementAsync {
// Strong capture of self
dispatch_async(dispatch_get_global_queue(
DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
self.count++; // Captures self strongly
});
}
@end
// Weak-strong dance for self
@interface ViewController : UIViewController
@property (nonatomic, strong) NSTimer *timer;
@end
@implementation ViewController
- (void)startTimer {
__weak typeof(self) weakSelf = self;
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0
repeats:YES
block:^(NSTimer *timer) {
__strong typeof(weakSelf) strongSelf = weakSelf;
if (!strongSelf) return;
// Safe to use strongSelf
[strongSelf updateUI];
}];
}
- (void)updateUI {
NSLog(@"Updating UI");
}
- (void)dealloc {
[self.timer invalidate];
}
@end
// Capturing objects vs primitives
Установить Objective-C Blocks and GCD в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл Objective-C Blocks and GCD?
Use when blocks (closures) and Grand Central Dispatch in Objective-C for concurrent programming including block syntax, capture semantics, dispatch queues, dispatch groups, and patterns for thread-safe asynchronous code.
Как установить скилл Objective-C Blocks and GCD?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл Objective-C Blocks and GCD запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic