Search code examples
objective-casynchronousautomatic-ref-countingobjective-c-blocksclgeocoder

Not assigning asynchronous objects in Objective-C?


Is there any reason not to do something this way:

[[[CLGeocoder alloc] init] geocodeAddressStr...

instead of this way:

CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressStr...

Because the completionHandler is a block, and the geocoder variable isn't used anymore, you might as wel not create it. Or am I overlooking things in the memory management department? I'm using ARC.


Solution

  • there is no need to separate the statements across two lines.

    you will need to create the CLGeocoder -- that is an instance method you are calling. However, you probably will not need to hold on to it.

    ARC and blocks are capable of capturing and retaining objc variables -- in addition to C and C++ PODs and C++ copy-constructible types.

    specifically, the block, if async, captures and retains the CLGeocoder (which you created) during the execution of geocodeAddressStr.... if the block were sync, then it would likely not need to capture the stack variables (block copy would not be needed) - it could just use the variables as-is, referencing them from the thread's stack.

    problems typically creep in when the programmer doesn't realize when explicit block copying is necessary.