如何在单独的文件中声明一组 Objective-c 块并将该文件包含在我的代码中?

How can I declare a set of Objective-c blocks in a separate file and include that file in my code?

我有一组 Objective-C 命名块,我需要跨多个 viewControllers。这些命名块将通过 dispatch_async().

执行

与其多次声明它们,我想声明一次(例如在 NSObject 子类 .h/.m 组合中),然后像任何标准子类一样 #import 它们。

我该怎么做?这让我抓狂。我尝试了几种方法,但解决方案一直在逃避我。请帮忙!

谢谢 陕

在您的 .h 文件中,像这样声明您的块变量:

#import <Cocoa/Cocoa.h>

extern int (^intReturningBlock)(int foo, int bar);
extern NSString* (^stringReturningBlock)(int foo, int bar);

然后在您的 .m 文件中,创建块变量:

#import "MyBlocks.h"

int (^intReturningBlock)(int foo, int bar) = ^int(int foo, int bar) {
    return foo + bar;
};

NSString* (^stringReturningBlock)(int foo, int bar) = ^NSString*(int foo, int bar) {
    NSNumber* tmp = @(foo + bar);
    return [tmp description];    
};

我的预感是您缺少的部分是声明中的 extern。这个网站是一个有用的参考:http://goshdarnblocksyntax.com