Question

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.

Was it helpful?

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.

OTHER TIPS

I always break such things down as in your second example, primarily for readability. It is my understanding that the compiler will treat these exactly the same as it will have to create the object to use it whether you assign it or no. I'd much rather see the variable with a name that makes it clear what the intentions are.

You can use the first method as you showed above. Memory management guidelines state that if you created an object in memory [...alloc] init] that you should be responsible for releasing it. If you are using ARC however, you don't need to release anything. After calling:

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

the created object will be released by the system when necessary. Losing the newly created object should be no problem as you said above that variable would not be used any more.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top