以块作为参数的方法的函数头约定/期望样式



我知道这是一个风格问题,而不是一个技术问题(这是一个小问题),但我想知道是否有一个当前的约定来声明文档注释的方法有块作为参数(特别是如果块本身接受参数)。

自从我开始用Objective-C开发以来,每当我遇到这个问题时,我都做了以下事情:

/**
 * This method does some awesome stuff and takes in a completion handler when it is 
 * done. I am wondering how to format the parameters of the completion block that is
 * passed in. I currently do this as I've written below, with the parameters of the
 * callback indented in line with the description of the callback itself.
 *
 * @param completion - callback to be triggered upon success.
 *                     @param (NSArray *) - an array that holds many objects
 *                     @param (SOPost *)  - a post onto StackOverflow
 */
- (void)someMethodWithBlock:(void (^)(NSArray *, SOPost *))completion {
    /* Function does whatever it's supposed to ... for example ... */
    NSArray *arr = [NSArray new];
    SOPost *post = [SOPost new];
    completion(arr, post);
}

这当然可以适用于任何语言(尤其是javascript),但我上面的例子是在Objective-C中,因为我处理的最多。

定义您的块,以便它的命名有意义。关于块所取内容的文档可以放在这里。

//These blocks are pretty self explanatory but more complicated ones could warrant documentation.
typedef void(^CallbackBlock)(id object);
typedef void(^AsyncLoadingBlock)(CompletionBlock completion);
typedef NSArray*(^FilterBlock)(NSArray *objects);
- (void)someMethodWithCallback:(CallbackBlock)callback; //callback accepts a SomeClass*
- (void)loadStuffWithCallback:(CallbackBlock)callback; //callback accepts an NSArray* of SomeData*
- (NSArray *)arrayByFilteringWithBlock:(FilterBlock)filterBlock //returns a new array filtered using a FilterBlock

最新更新