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

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:
Class A creates a CLLocationManager object
A is set as the delegate for the CLLocationManager object
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!

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.

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

Related

How to manage unsafe_unretained ivars/properties?

I started objective-c and iOS a couple of weeks ago (worth bearing in mind), and I apologise in advance for the awful diagram!!
The above diagram shows the structure of my calls to a webservice. Thin arrows denote an object creating another object, whereas thick arrows denote an object holding a strong (retained) reference to the pointed-to object.
I believe that this contains what is called a "circular reference" and will create problems when it comes to deallocating the objects.
I understand that the easy answer would be to replace some of the strong references to weak ones, which I'd love to do, except my project is also targeting iOS 3.2 (not my decision - I can't really change this fact!). So, I think I'm right in saying that I have to use __unsafe_unretained instead, but I'm quite worried about the fact that these won't auto-zero, as I'll end up with EXC_BAD_ACCESS problems when objects get deallocated...
So my problem is firstly that I have circular references. To solve, I would have to use __unsafe_unretained, which leads to my second problem: How to correctly manage these?
A question that might be related is: How does NSURLConnection manage it's strong references? I have heard from various sources that it retains its delegate? So...if I retain an NSURLConnection, (and am also its delegate) and it retains me, this would also be a circular reference, no? How does it get around my problem?
Any advice is very welcome!
Regards,
Nick
When a parent has a reference to a child object, it should use a strong reference. When a child has a reference to it's parent object, it should use a weak reference, aka unsafe_unretained.
By convention, delegate relationships in iOS are usually weak references, so you'll find that most delegate properties on Apple's own classes are declared as unsafe_unretained.
So your controller retains the services that it is using, but the services only weakly link back to the controller. That way, if the controller is released, the whole lot can be safely disposed of without any circular references.
The danger with this is that if the web service is doing some long-running task, and the controller gets released before it has finished, the service is left with a dangling pointer to it's now-deallocated delegate. If it tries to send a message to the delegate, such as "I have finished" it will crash.
There are a few approaches to help solve this (they aren't mutually exclusive - you should try to do them all whenever possible):
1) Always set the delegate properties of your services to nil in your controller's dealloc method. This ensures that when the controller is released, the delegate references to it are set to nil (sort of a crude, manual equivalent of what ARC's weak references do automatically).
2) When creating your own service classes that have delegates, make them retain their delegate while they are running and then release the delegate when they are done. That way the delegate object can't get deallocated while the service is still sending it messages, but it will still get released once the service has finished (NSTimer's and NSURLConnections both work this way - they retain their delegate while they are running and release it when they are done).
3) Try not to have long-running services owned by something transient like a view controller. Consider creating singleton objects (shared static object instances) that own your services, that way the service can do it's job in the background regardless of what's going on in the view layer. The controller can still call the service, but doesn't own it - the service is owned by a static object that will exist for the duration that the app is running, and so there's no risk of leaks or premature releases. The service can communicate with the controller via NSNotifications instead of delegate calls, so there is no need for it to have a reference to an object that may vanish. NSNotifications are a great way to communicate between multiple classes without creating circular references.
All of your questions and concerns are correct, and this problem with the previous use of assign (now better named __unsafe_unretained) is why Apple developed auto-zeroing for weak. But we've dealt reasonably safely with assign delegates for many years, so as you suspect, there are ways to do it.
First, as a matter of practice, you should always clear yourself as the delegate when your release an object you were delegate for. Pre-ARC, this was traditionally done in dealloc:
- (void)dealloc {
[tableView_ setDelegate:nil];
[tableView_ release];
tableView_ = nil;
}
You should still include that setDelegate:nil in your dealloc if delegate is __unsafe_unretained. This will address the most common form of the problem (when the delegate is deallocated before the delegating object).
Regarding NSURLConnection, you are also correct that it retains its delegate. This is ok because it has a lifespan typically much shorter than its delegate (versus a table view delegate which almost always has the same lifespan as the table view). See " How to work around/handle delegation EXC_BAD_ACCESS errors? Obj C " for more discussion on this in a pre-ARC context (the same concepts apply in the new world of strong/weak).

Object going out of scope, but delegate is set, using ARC

I'm so very sorry for the unclear title, but I can't explain it shortly.
I am basically wondering what happens if you use ARC and you have a method like this:
- (void)fooMethod:(NSURLRequest *)fooReq
{
NSURLConnection *fooConn = [NSURLConnection connectionWithRequest:fooReq delegate:self];
[fooConn start];
}
So fooConn goes out of scope at the end of the fooMethod, but will I still receive callbacks? In other words: because there aren't any more references, will it get dealloc'd (or something like that) immediately, or will it stay in memory and handle the request because the delegate is still set?
That totally depends on what NSURLConnection does behind the scenes. If the retain count drops to zero, then fooConn will be dealloc'ed still and one would assume no more callbacks would be made then.
Now, I think that NSURLConnection behind the scenes does get retained somewhere in the hierarchy of things so you would in fact receive callbacks. However with NSURLConnection I usually keep a strong reference to it lying around to be on the safe side. After all, you as the caller of it want to own it and you want to ensure that you will keep getting the delegate callbacks and not be at the mercy of whatever happens to it under the hood.
So, in short, if I were you I'd keep a strong reference to it to ensure you won't have to worry.
From the Apple docs:
- (id)initWithRequest:(NSURLRequest *)request delegate:(id < NSURLConnectionDelegate >)delegate startImmediately:(BOOL)startImmediately
The connection retains delegate. It releases delegate when the connection finishes loading, fails
fooConn is a local variable without any ownership qualifier so ARC will infer it as strong. Therefore ARC will retain the value returned by connectionWithRequest:delegate: when storing it into foxConn; and when exiting fooMethod: ARC will clean up by releasing fooConn.
That the delegate references the current instance will have no effect on this.
If you wish the NSURLConnection to exist after fooMethod: returns one way is to store it into an instance variable (which ARC also infers as strong, so no ownership qualifier required there either). If you do this when the class instance itself is no longer reference ARC will release the NSURLConnection.

Can I just release the top object (iPhone)?

If I release the object that's holding a reference to the variable that I need to release, is that sufficient? Or must I release at every level of the containment hierarchy? I fear that my logic comes from working with a garbage collector for too long.
For instance, I assigned to this property of a UIPickerView instance by hand instead of using IB
#property(nonatomic, assign) id<UIPickerViewDelegate> delegate
Since it's an assign property, I can't just release the reference after I assign it. When I finally release my UIPickerView instance, do I need to do this:
[singlePicker.delegate release];
[singlePicker release];
or is the second line sufficient?
Also: Are these assign properties the norm, or is that mostly for Interface Builder? I thought that retain properties were the normal thing to expect.
The properties are declared assign instead of retain for a reason - delegates are not owned by their holders and they don't call release on them. Otherwise there would be a problem with circular references. You however have to call release on the object you use as the delegate somewhere if you own them.
If delegates were retained, imagine the following situation:
a takes b as a delegate, retains b
b takes a as a delegate, retains a
Now you have a circular reference - without ugly cleanup code that explicitly tells them to release their delegates, both of the objects will never be deallocated.
The subject is treated in Delegation and the Cocoa Application Frameworks:
Delegating objects do not (and should not) retain their delegates. However, clients of delegating objects (applications, usually) are responsible for ensuring that their delegates are around to receive delegation messages. To do this, they may have to retain the delegate in memory-managed code. This precaution applies equally to data sources, notification observers, and targets of action messages. Note that in a garbage-collection environment, the reference to the delegate is strong because the retain-cycle problem does not apply.

Objective-C Delegate Pointers

If we write the following code:
ExplorerAppDelegate * appDelegate = (ExplorerAppDelegate *)[[UIApplication sharedApplication] delegate];
This makes a reference to the original delegate pointer, but:
Does it increase the reference count?
Do we have to explicitly call as [ExplorerAppDelegate retain] right after, or not at all?
What's happening, exactly?
After we've used this, we should also do a [ExplorerAppDelegate release] in the dealloc method, right?
No, it does not increase the retain count.
The convention in Objective-C is that objects you are given should be memory managed by yourself - but in the case of obtaining a shared common resource like the app delegate, the memory is maintained elsewhere and of course (with this being the app delegate) you know that it will always be "alive" as long as your class is... so there is no need to retain the reference.
In most uses of delegates, instead of fetching a delegate you are given one, and that reference is not retained either. In that case whoever gave you the delegate is also responsive for clearing out the delegate link before the delegate is released.
The reason you don't want to generally retain delegate references is that it can prevent some objects from being deallocated, for instance if one class is a delegate of a class that ues the other class as a delegate.
The reference count will not be increased
You should retain it if you want to be sure that it isn't deallocated while you have a pointer to it
You should only release it if you retained it
So basically, if you're only using the object in a single function, you probably don't need retain or release it. If it exists when you get it, then it's (probably) not going to be deallocated by the end of the function. If you're keeping it around, in an ivar (member variable) for example, then you should retain it and release it later.
See the "Weak References to Objects" in Memory Management Programming Guide for Cocoa for the official answer. Pointers to delegates are one of the possible exception cases to the memory management rules.

Is it bad practice for a delegate to have a reference to the object for which it is the delegate?

I'm using the delegate pattern for one of my objects. My idea is that I will be able to swap the delegate out later for a different delegate implementing a different strategy. I suppose this is just as much the strategy pattern as the delegate pattern.
My question is, is it bad practice for my delegate to have a reference back to the object for which it is the delegate? There are a couple properties of that object that I need to have access to regardless of which delegate/strategy I use. If this is bad form, how should I get access to the properties?
Not necessarily. For example, it's quite common for a "controller"-type object to create data objects and views and make itself the delegate of some of those objects in order to properly control things.
It is not at all bad practice. The delegate pattern allows for a class to have a generic way to talk to any number of objects as long as the implement the same protocol. But the class on which you set the delegate also will usually have a number of public properties or methods that allow you to query or alter what the class is doing, in response to which the class may in turn trigger a number of the delegate calls. So you need a reference of the class to which you are the delegate, in order to tell the object to do something different than it is already, and of course to release it when you are through with it!
This is also why it's important to always have any delegate properties as assign, and not retain, properties. That way when the originating class is released it will actually be released, instead of having delegate objects it is holding onto causing a retain loop that keeps both around.
It's also why whenever you are being released, you should set the delegate reference to nil in anything you may have a delegate reference set. This way a class will not have an invalid delegate reference if the delegate is released before the class that uses a delegate.
Generally a dependency should not have a reference back to the dependent object, as this would be a classical circle reference. To avoid having a back-reference you can supply the needed properties as arguments in a delegate method, or you move the properties themselves into the delegate.
I'd say yes, it's bad practice. The idea behind a delegate is that it's effectively a standalone object that receives messages about the object for which it is the delegate (the "delegator"). The delegator should have a reference to the delegate, not the other way around, otherwise it's not a true delegation relationship anymore.
A preferred way to accomplish what you're asking is to provide the sending object along with whatever message your delegate receives. For example, on your delegate, instead of having a delegator property and then receiving, for example, a didDoSomething:(id)anObject method, you could remove the delegator property and send the message delegator:(id)anObject didDoSomething:(id)anotherObject. This way, you keep the delegate distinct from the delegator, but still get access to the delegator's properties when you need them.
This way also has the advantage of not providing access to the delegator in methods when you don't truly need it; for example, your delegate could have a didDoSomething method that takes no arguments, not even a delegator, and is just used for logging, as well as a delegator:(id)anObject didSomethingElse:(id)anotherObject method that calls some properties on the delegator and is much more involved.
Finally, this method allows you to use the same delegate for multiple delegators, since you don't need to update a delegator property for each delegate object.
For a good example of how this works, take a look at the NSURLConnection documentation, specifically its delegate methods - a lot of them take the form connection:didDoSomething:, where the first argument is the connection calling the delegator. Developers commonly define a single connection delegate for multiple connections, implementing their delegate methods to do different things depending on properties of the NSURLConnection object passed in.