Search code examples
objective-cblock

How can I modify an ObjC method's parameters within a block?


If I have an Objective-C method that takes an object parameter, and said method uses a block to do its work internally, is there a way to modify that object from within the block?

It is my understanding that blocks capture variables from their parent scope by referring to them within the block, and that they are copied by default. And if I want to be able to modify rather than work with a copy of a surrounding object, I can prefix its declaration with __block, but I'm unable to do so with method parameters since I didn't declare it myself, right?

For example:

- (void)doWorkWithString:(NSString *)someString
{
    [NSFoo doAwesomeClassMethodWithBlock:^{
        // How can I modify someString here directly?
        // By just changing someString, I'm changing the captured copy
    }];
}

Solution

  • What you say about capture is correct; what you probably want to do is supply the objects that should be the subject of the block as arguments to it — much like if you were calling a C function. So e.g.

    void (^ someBlock)(NSString *) =
        ^(NSString *someString)
        {
            NSLog(@"length is %d", [someString length]);
        };
    
    ...
    
    someBlock(@"String 1");
    someBlock(@"A second string");