Token导航 LogoToken导航TokenDH.com
前端设计需要联网github未标认证来源可访问clear审计通过

objective-c-blocks-and-gcdObjective C 块和 GCD

Agent Skill

用于辅助前端页面、组件、样式和交互逻辑的开发与维护。它适合让 Agent 生成或审查 React、Next.js、Vue、Tailwind、CSS 等相关代码,整理组件结构,或定位布局和性能问题。使用时需要结合项目现有设计系统、路由和构建方式,避免只生成孤立片段;涉及页面改动时,应配合本地预览和构建检查确认视觉效果。

总安装

20,340

周安装

549

GitHub Stars

142

下载量

4,027
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

3

许可证

MIT

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:objective-c-blocks-and-gcd(Objective C 块和 GCD)
来源仓库:https://github.com/thebushidocollective/han
仓库路径:skills/objective-c-blocks-and-gcd
安装命令:
npx skills add https://github.com/thebushidocollective/han --skill 'Objective-C Blocks and GCD'
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

skills.shnpx skills
npx skills add https://github.com/thebushidocollective/han --skill 'Objective-C Blocks and GCD'

简介

Objective-C 块和 GCD 用于辅助前端页面、组件、样式和交互逻辑的开发与维护。

  • 适用于生成或审查 React、Next.js、Vue、Tailwind、CSS 等相关代码的场景。
  • 通过 GitHub 仓库安装,使用 npx skills add 命令添加技能,需结合项目现有设计系统使用。
  • 涉及页面改动时应配合本地预览和构建检查确认视觉效果,避免生成孤立片段。
  • objective-c-blocks-and-gcd 属于前端设计类 Skill,可作为该场景下的辅助能力补充。

SKILL.md

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
void objectCaptureExample(void) {
    NSMutableString *string = [NSMutableString stringWithString:@"Hello"];

    void (^block)(void) = ^{
        [string appendString:@" World"]; // Can mutate object
        NSLog(@"%@", string);
    };

    block(); // Prints "Hello World"
}

// Block retain cycles
@interface NetworkManager : NSObject
@property (nonatomic, copy) void (^completion)(NSData *data);
@end

@implementation NetworkManager

- (void)fetchData {
    __weak typeof(self) weakSelf = self;

    self.completion = ^(NSData *data) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if (!strongSelf) return;

        [strongSelf processData:data];
    };
}

- (void)processData:(NSData *)data {
    NSLog(@"Processing: %@", data);
}

@end

// Capturing __block objects
void blockObjectExample(void) {
    __block NSMutableArray *array = [NSMutableArray array];

    void (^addBlock)(id) = ^(id object) {
        [array addObject:object]; // Can mutate and reassign
    };

    addBlock(@"Item 1");
    addBlock(@"Item 2");

    array = [NSMutableArray array]; // Can reassign
}

Use __weak to avoid retain cycles when capturing self, and __block to allow mutation of captured variables.

Dispatch Queues

GCD uses dispatch queues to manage concurrent execution, with serial queues executing tasks sequentially and concurrent queues executing them in parallel.

// Main queue (serial, main thread)
dispatch_async(dispatch_get_main_queue(), ^{
    // Update UI
    NSLog(@"On main thread");
});

// Global concurrent queues
dispatch_queue_t highPriorityQueue = dispatch_get_global_queue(
    DISPATCH_QUEUE_PRIORITY_HIGH, 0);
dispatch_queue_t defaultQueue = dispatch_get_global_queue(
    DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_queue_t lowPriorityQueue = dispatch_get_global_queue(
    DISPATCH_QUEUE_PRIORITY_LOW, 0);
dispatch_queue_t backgroundQueue = dispatch_get_global_queue(
    DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);

// Async execution on global queue
dispatch_async(defaultQueue, ^{
    // Background work
    NSLog(@"Background work");

    dispatch_async(dispatch_get_main_queue(), ^{
        // Update UI on main queue
        NSLog(@"UI update");
    });
});

// Custom serial queue
dispatch_queue_t serialQueue = dispatch_queue_create("com.example.serial", DISPATCH_QUEUE_SERIAL);

dispatch_async(serialQueue, ^{
    NSLog(@"Task 1");
});

dispatch_async(serialQueue, ^{
    NSLog(@"Task 2");
});

// Custom concurrent queue
dispatch_queue_t concurrentQueue = dispatch_queue_create(
    "com.example.concurrent", DISPATCH_QUEUE_CONCURRENT);

dispatch_async(concurrentQueue, ^{
    NSLog(@"Concurrent task 1");
});

dispatch_async(concurrentQueue, ^{
    NSLog(@"Concurrent task 2");
});

// Synchronous dispatch (blocks until complete)
__block NSString *result;
dispatch_sync(serialQueue, ^{
    result = @"Computed value";
});
NSLog(@"Result: %@", result);

// Dispatch after (delayed execution)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC),
               dispatch_get_main_queue(), ^{
    NSLog(@"Executed after 2 seconds");
});

// Dispatch once (thread-safe singleton)
+ (instancetype)sharedInstance {
    static id sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

// Quality of service (iOS 8+)
dispatch_queue_t userInitiatedQueue = dispatch_get_global_queue(
    QOS_CLASS_USER_INITIATED, 0);
dispatch_queue_t utilityQueue = dispatch_get_global_queue(QOS_CLASS_UTILITY, 0);

dispatch_async(userInitiatedQueue, ^{
    // User-initiated work (high priority)
});

Use main queue for UI updates, global queues for background work, and custom queues for synchronization and ordered execution.

Dispatch Groups

Dispatch groups coordinate multiple async operations, notifying when all tasks complete.

// Basic dispatch group
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_get_global_queue(
    DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_group_async(group, queue, ^{
    NSLog(@"Task 1");
});

dispatch_group_async(group, queue, ^{
    NSLog(@"Task 2");
});

dispatch_group_async(group, queue, ^{
    NSLog(@"Task 3");
});

dispatch_group_notify(group, dispatch_get_main_queue(), ^{
    NSLog(@"All tasks complete");
});

// Waiting for group completion
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
NSLog(@"After wait");

// Manual enter/leave
dispatch_group_t manualGroup = dispatch_group_create();

dispatch_group_enter(manualGroup);
[self fetchDataWithCompletion:^(NSData *data, NSError *error) {
    NSLog(@"Data fetched");
    dispatch_group_leave(manualGroup);
}];

dispatch_group_enter(manualGroup);
[self fetchImageWithCompletion:^(UIImage *image, NSError *error) {
    NSLog(@"Image fetched");
    dispatch_group_leave(manualGroup);
}];

dispatch_group_notify(manualGroup, dispatch_get_main_queue(), ^{
    NSLog(@"All fetches complete");
});

// Practical example: loading multiple resources
- (void)loadAllResources {
    dispatch_group_t resourceGroup = dispatch_group_create();
    __block NSData *userData = nil;
    __block NSData *settingsData = nil;
    __block UIImage *profileImage = nil;

    dispatch_group_enter(resourceGroup);
    [self fetchUserDataWithCompletion:^(NSData *data) {
        userData = data;
        dispatch_group_leave(resourceGroup);
    }];

    dispatch_group_enter(resourceGroup);
    [self fetchSettingsWithCompletion:^(NSData *data) {
        settingsData = data;
        dispatch_group_leave(resourceGroup);
    }];

    dispatch_group_enter(resourceGroup);
    [self fetchProfileImageWithCompletion:^(UIImage *image) {
        profileImage = image;
        dispatch_group_leave(resourceGroup);
    }];

    dispatch_group_notify(resourceGroup, dispatch_get_main_queue(), ^{
        // All resources loaded
        [self updateUIWithUser:userData settings:settingsData image:profileImage];
    });
}

- (void)fetchUserDataWithCompletion:(void (^)(NSData *))completion {
    dispatch_async(dispatch_get_global_queue(
        DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if (completion) completion([NSData data]);
    });
}

- (void)fetchSettingsWithCompletion:(void (^)(NSData *))completion {
    dispatch_async(dispatch_get_global_queue(
        DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if (completion) completion([NSData data]);
    });
}

- (void)fetchProfileImageWithCompletion:(void (^)(UIImage *))completion {
    dispatch_async(dispatch_get_global_queue(
        DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if (completion) completion([[UIImage alloc] init]);
    });
}

- (void)updateUIWithUser:(NSData *)user settings:(NSData *)settings
                   image:(UIImage *)image {
    NSLog(@"Updating UI with all resources");
}

Dispatch groups are essential for coordinating multiple async operations and ensuring all complete before proceeding.

Dispatch Barriers and Synchronization

Barriers provide synchronized access to shared resources in concurrent queues.

// Dispatch barrier for reader-writer pattern
@interface ThreadSafeCache : NSObject
@property (nonatomic, strong) dispatch_queue_t concurrentQueue;
@property (nonatomic, strong) NSMutableDictionary *cache;
@end

@implementation ThreadSafeCache

- (instancetype)init {
    self = [super init];
    if (self) {
        self.concurrentQueue = dispatch_queue_create(
            "com.example.cache",
            DISPATCH_QUEUE_CONCURRENT
        );
        self.cache = [NSMutableDictionary dictionary];
    }
    return self;
}

// Multiple readers allowed
- (id)objectForKey:(NSString *)key {
    __block id object;
    dispatch_sync(self.concurrentQueue, ^{
        object = self.cache[key];
    });
    return object;
}

// Exclusive writer with barrier
- (void)setObject:(id)object forKey:(NSString *)key {
    dispatch_barrier_async(self.concurrentQueue, ^{
        self.cache[key] = object;
    });
}

// Synchronous barrier write
- (void)setObjectSync:(id)object forKey:(NSString *)key {
    dispatch_barrier_sync(self.concurrentQueue, ^{
        self.cache[key] = object;
    });
}

@end

// Semaphores for limiting concurrency
- (void)downloadImagesWithLimit:(NSArray<NSURL *> *)urls {
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(3);
    // Max 3 concurrent
    dispatch_queue_t queue = dispatch_get_global_queue(
        DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    for (NSURL *url in urls) {
        dispatch_async(queue, ^{
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

            // Download image
            NSLog(@"Downloading: %@", url);
            [NSThread sleepForTimeInterval:1.0]; // Simulate download

            dispatch_semaphore_signal(semaphore);
        });
    }
}

// Dispatch apply for parallel loops
- (void)processItems:(NSArray *)items {
    dispatch_apply(items.count, dispatch_get_global_queue(
        DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(size_t index) {
        id item = items[index];
        NSLog(@"Processing item %zu: %@", index, item);
        // Process item in parallel
    });
}

// Mutex alternative with dispatch_sync
@interface Counter2 : NSObject
@property (nonatomic, strong) dispatch_queue_t syncQueue;
@property (nonatomic, assign) NSInteger count;
@end

@implementation Counter2

- (instancetype)init {
    self = [super init];
    if (self) {
        self.syncQueue = dispatch_queue_create("com.example.counter", DISPATCH_QUEUE_SERIAL);
        self.count = 0;
    }
    return self;
}

- (void)increment {
    dispatch_sync(self.syncQueue, ^{
        self.count++;
    });
}

- (NSInteger)currentCount {
    __block NSInteger value;
    dispatch_sync(self.syncQueue, ^{
        value = self.count;
    });
    return value;
}

@end

Barriers ensure exclusive write access while allowing concurrent reads, ideal for thread-safe caches and data structures.

Block-Based APIs

Modern Cocoa APIs extensively use blocks for callbacks, providing cleaner alternatives to delegate patterns.

// NSURLSession with blocks
- (void)fetchURL:(NSURL *)url {
    NSURLSession *session = [NSURLSession sharedSession];

    NSURLSessionDataTask *task = [session dataTaskWithURL:url
        completionHandler:^(NSData *data, NSURLResponse *response,
                            NSError *error) {
        if (error) {
            NSLog(@"Error: %@", error);
            return;
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            // Process data on main thread
            NSLog(@"Data received: %@", data);
        });
    }];

    [task resume];
}

// UIView animations with blocks
- (void)animateView:(UIView *)view {
    [UIView animateWithDuration:0.3
                     animations:^{
        view.alpha = 0.0;
        view.transform = CGAffineTransformMakeScale(0.5, 0.5);
    } completion:^(BOOL finished) {
        if (finished) {
            [view removeFromSuperview];
        }
    }];
}

// NSNotificationCenter with blocks
- (void)observeNotifications {
    id observer = [[NSNotificationCenter defaultCenter]
        addObserverForName:UIApplicationDidEnterBackgroundNotification
                    object:nil
                     queue:[NSOperationQueue mainQueue]
                usingBlock:^(NSNotification *note) {
        NSLog(@"App entered background");
    }];

    // Store observer to remove later
}

// Custom block-based API
typedef void (^ProgressBlock)(CGFloat progress);
typedef void (^CompletionBlock2)(BOOL success, NSError *error);

@interface Downloader : NSObject
- (void)downloadFile:(NSURL *)url
            progress:(ProgressBlock)progress
          completion:(CompletionBlock2)completion;
@end

@implementation Downloader

- (void)downloadFile:(NSURL *)url
            progress:(ProgressBlock)progress
          completion:(CompletionBlock2)completion {
    dispatch_async(dispatch_get_global_queue(
        DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // Simulate download with progress
        for (NSInteger i = 0; i <= 100; i += 10) {
            [NSThread sleepForTimeInterval:0.1];

            dispatch_async(dispatch_get_main_queue(), ^{
                if (progress) {
                    progress(i / 100.0);
                }
            });
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion) {
                completion(YES, nil);
            }
        });
    });
}

@end

// Using custom block API
- (void)downloadExample {
    Downloader *downloader = [[Downloader alloc] init];
    NSURL *url = [NSURL URLWithString:@"https://example.com/file.zip"];

    [downloader downloadFile:url
                    progress:^(CGFloat progress) {
        NSLog(@"Progress: %.0f%%", progress * 100);
    } completion:^(BOOL success, NSError *error) {
        if (success) {
            NSLog(@"Download complete");
        } else {
            NSLog(@"Download failed: %@", error);
        }
    }];
}

Block-based APIs provide inline callback handling without the boilerplate of delegation or notification observers.

Best Practices

  1. Copy blocks when storing in properties to move them from stack to heap and prevent crashes from dangling pointers
  2. Use weak-strong dance for self capture in blocks stored as properties to break retain cycles
  3. Dispatch UI updates to main queue using dispatch_async to ensure thread-safe UI modifications
  4. Prefer dispatch groups over nested callbacks to coordinate multiple async operations cleanly
  5. Use dispatch barriers for reader-writer patterns to allow concurrent reads while ensuring exclusive writes
  6. Create custom queues for synchronization rather than using global queues to avoid contention and priority issues
  7. Check for nil before calling blocks to prevent crashes from unimplemented optional block parameters
  8. Use dispatch_once for thread-safe singletons to ensure exactly-once initialization without locks
  9. Limit concurrency with semaphores when accessing rate-limited resources like network connections
  10. Profile with Instruments to identify queue contention, thread explosion, and performance bottlenecks

Common Pitfalls

  1. Creating retain cycles with strong self capture in blocks stored as properties causes memory leaks
  2. Not copying blocks when storing them leads to crashes when stack-allocated blocks go out of scope
  3. Using dispatch_sync on current queue causes deadlock; never sync dispatch to the queue you're on
  4. Forgetting to dispatch to main queue for UI updates causes crashes or undefined behavior
  5. Overusing dispatch_sync blocks threads unnecessarily; prefer async dispatch for better performance
  6. Not balancing dispatch_group_enter/leave causes group notifications to never fire or fire prematurely
  7. Accessing mutable state without synchronization from multiple queues causes race conditions and data corruption
  8. Creating too many custom queues wastes resources; reuse queues where appropriate
  9. Using global queues for barriers doesn't work as barriers require custom concurrent queues
  10. Blocking in weak-strong dance without nil check can cause crashes if weakSelf becomes nil during execution

When to Use This Skill

Use blocks and GCD when building iOS, macOS, watchOS, or tvOS applications that require asynchronous operations, concurrent processing, or callback-based APIs.

Apply dispatch queues for background processing, network calls, file I/O, or any operation that shouldn't block the main thread.

Employ dispatch groups when coordinating multiple async operations that must all complete before proceeding, like loading multiple resources.

Leverage dispatch barriers for thread-safe data structures that support concurrent reads and exclusive writes.

Use block-based APIs when designing modern Objective-C interfaces that provide inline callback handling without delegate boilerplate.

Resources

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

04

需要参考平台分布和安装热度时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

补充不同宿主或平台的使用分布数据

能力 5

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

OpenCode

29.22%
按下载量换算1,177

Claude Code

21.82%
按下载量换算879

Codex

19.45%
按下载量换算783

windsurf

13.15%
按下载量换算530

Cursor

8.72%
按下载量换算351

Antigravity

3.83%
按下载量换算154

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源字段存在多来源差异,先按来源优先级自动处理,无法消解时进入异常复核队列。

来源信息

继续浏览同类 Skills