how to add an extra argument to a block

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-02 11:49:59

I don't know that class specifically, but in general any block "captures" variables used inside the block. So this should "just work":

int fileNum = x;
CTCoreAttachment* fullAttachment = 
    [attachment fetchFullAttachmentWithProgress:^(size_t curr, size_t max) {
    // ..
    NSLog(@"::: this progress belongs to element %d", fileNum);
}];

The block captures the value of the variable at the moment when the block is created.

(It would be slightly different if fileNum is declared with the __block modifier, but that is probably not relevant to your problem.)

the way I figured this out is by breaking it into two steps:

  1. implementing what I want through delegation
  2. converting the delegation into a block based approach.

and since this problem is kind of hard to explain by english, I figured it's best explained by sample code :)

Delegation Solution:

// AttachmentDownloader.m
+(void)runMultiple:(NSDictionary *)attachmentTree 
      withDelegate:(id<AttachmentDownloaderDelegate>)delegate  {
    ..

    CTCoreAttachment* fullAttachment = 
       [attachment fetchFullAttachmentWithProgress:^(size_t curr, size_t max) {
            NSLog(@"::: this is curr: %zu", curr);
            NSLog(@"::: this is max: %zu\n\n", max);
            NSLog(@"::: this is attachment uid %@", [message uid]);
            [delegate deliverProgressWithInfo:@{@"uid":[message uid],
                                                @"curr":[NSNumber numberWithInt:curr],
                                                @"max":[NSNumber numberWithInt:max]}];
     }];


// FileBucket.m
[AttachmentDownloader runMultiple:attachmentTree withProgress:^(size_t curr, size_t max) {
    NSLog(@"::: this is curr: %zu", curr);
    NSLog(@"::: this is max: %zu\n\n", max);
} withDelegate:self];

// delegate method
-(void)deliverProgressWithInfo:(NSDictionary *)dict {
    NSLog(@"filebucket: this is info being updated %@", dict);
}

Block Solution:

// AttachmentDownloader.m
+(void)runMultiple:(NSDictionary *)attachmentTree 
      withProgress:(void(^)(NSDictionary *))block {
    ..

    CTCoreAttachment* fullAttachment = 
        [attachment fetchFullAttachmentWithProgress:^(size_t curr, size_t max) {
        NSLog(@"::: this is curr: %zu", curr);
        NSLog(@"::: this is max: %zu\n\n", max);
        NSLog(@"::: this is attachment uid %@", [message uid]);
        block(@{@"uid":  [message uid],
                @"curr": [NSNumber numberWithInt:curr],
                @"max":  [NSNumber numberWithInt:max]});
    }];


// FileBucket.m
-(void)downloadSelectedAttachments {
    NSDictionary* attachmentTree = [self getAttachmentTree];
    [AttachmentDownloader runMultiple:attachmentTree withProgress:^(NSDictionary * dict) {
        NSLog(@"filebucket: this is info being updated %@", dict);
    }];
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!