An object, working asynchronously, disappears because there is no reference to it. Is this expected?

StackOverflow https://stackoverflow.com/questions/23497015

Frage

I am new to Objective-C and I just wanted to confirm whether what I'm observing is correct.

This is what's going on:

  1. Class A creates a CLLocationManager object
  2. A is set as the delegate for the CLLocationManager object
  3. Location services are activated (in order to have the CLLocationManager object call A with location updates)

However, location updates are not received unless a reference to the CLLocationManager object is kept somewhere.

I assume that this is because of ARC. But I am asking because my expectation was that CLLocationManager would not be deallocated: it has work to do, and the delegate methods receive a reference to the CLLocationManager, so why keep an extra property!

Is this interpretation correct?

Is there anything else one can do to keep the CLLocationManager object working other than have a property pointing to it?

As an experiment I tried running the steps above within a dispatch queue, but the location updates were not received.

Thanks!

War es hilfreich?

Lösung

I guess your big question is whether this behavior is common and expected. The answer is the following - it depends. It is an implementation decision. I've seen frameworks working both ways. Usually, you can guess the behavior from the method naming.

For example, a new instance of CLLocationManager has to be created before use. Once you have to call alloc and init, you should always keep the reference.

On the other hand, in frameworks where you don't create a new object, you don't need to hold the reference - for example [NSNotificationCenter defaultCenter] or [UIApplication sharedApplication]. The framework holds the reference for you.

Frameworks which use class methods (e.g. STTwitter) also typically hold the references for you.

Your following assumption

and the delegate methods receive a reference to the CLLocationManager

is wrong. The delegate is only a set of methods. It doesn't hold anything if you don't implement it explicitly. Note that you have to also keep a reference to the delegate. The manager won't keep it alive.

Andere Tipps

If you are not keeping a reference to the CLLocationManager object it will be deallocated once you reach the end of the scope

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top