ViewDidLoad and ARC and XIBs - objective-c

Given that we are writing code with ARC, should I nil properties in viewDidUnload, that are instantiated from:
XIB (here the nilling is sometimes generated from IDE)
from initialiser and have not IBOutlet
that are weak
?

The purpose of viewDidUnload is to give your app a chance to remove references to user interface objects that may no longer exist because the view was removed upon receiving a memory warning. Thus:
You should be setting any user interface controls to nil (because the view is being unloaded). Unnecessary for weak properties (and they generally should be weak per Apple guidance on this topic), but if Xcode inserts it in for you, it's not a problem. For guidance on what to do in viewDidUnload see the "Memory Warnings" section of the Resource Programming Guide: The Nib Files.
And for non-user interface objects that you set up in viewDidLoad, I'd be wary about just blindly setting those to nil in viewDidUnload, especially if you're not using ARC (e.g. if you accidentally nil the instance variable, you might cause a leak). And you probably want to balance the amount of memory that will be recovered versus the "cost" of re-retrieving that data (e.g. if it's from some remote server). Regardless, I'd suggest that you handle the freeing of memory for non-UI objects in didReceiveMemoryWarning.
In my mind, I view viewDidUnload as a chance to make sure I'm not maintaining references to user interface objects that might no longer exist, and I use didReceiveMemoryWarning to empty caches or other non-UI related items that I can safely purge to recover some memory. And if you're concerned about iOS 6, note that the handling of viewDidUnload may be changing, and while the NDA precludes us from discussing it publicly, I might advise that you may want to refer to the iOS 6 Beta 4 Release Notes and look for references to viewDidUnload.

Your general rules:
nil all strong IBOutlets only. Leave weak ones alone.
nil all properties instantiated in viewDidLoad, and not init, initWithCoder: and initWithNibName:bundle:.
You should also nil properties that are recreated "on-the-fly" or have a nil check, to free up more memory.

Related

Why would app crash if delegate uses assign instead of weak?

I have seen report that if a delegate uses assign instead of weak, the app crashes. Why?
Example: RestKit
With ARC a weak ivar will be automatically set to nil when the ivar object is deallocated. That means that if your delegate is destroyed and you try to message the delegate you'll just message nil, which has no effect. If the delegate ivar was merely assign then you would message some chunk of memory that no longer contained a valid object.
The only difference between assign and weak is that weak does extra work to avoid some common crashing bugs. The drawback, however, is that assign has much better performance than weak.
Specifically, when an object is released, any weak property pointing to it will be set to nil. Any assign property pointing to it will be left pointing at the object that is no-longer used.
And some other object is likely to be placed at the same location in memory as the old object, so suddenly instead of an instance of MyDelegate you might have a UIImage object in the same location in memory, or perhaps a float value, or anything at all.
So you should always use weak, for everything. But if you run into performance problems, check if weak is the cause, and consider switching to assign after learning how to avoid those crashing bugs.
For a delegate you should pretty much always use weak. Normally you'd only pick assign if you are dealing with millions of objects. Typically that doesn't happen with delegates.

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).

Settings IBOutlets to nil in dealloc

In the section titled 'Memory Warnings' here http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmNibObjects.html, I don't follow why the IBOutlet is set to nil in the dealloc. If
self.anOutlet = nil
causes a crash as mentioned in the topic, why are they setting the ivar to nil?
In general, why would you set an ivar to nil in the dealloc when you are already calling release?
After a release, the pointer is essentially invalid and accessing it again may cause a crash. By setting a variable to nil after release you prevent that crash from happening. There's no harm in accessing a nil pointer.
The example you've linked to simply demonstrates why it's always a good idea to set a variable or ivar to nil after release, even when it looks like the variable/ivar won't be accessed again.
In the example, the anOutlet ivar is actually accessed by the superclass after your dealloc method, so if you don't set it to nil you will get a crash. Scenarios like that are very hard to spot just by looking at the code, so it's a good idea to nil every variable after release, even in dealloc.
Sending a message on an object that is released causes a crash, sending a message to a nil object is ignored.
Sometimes a crash is a good thing, and a quick solution would hide a deeper problem. Calling a released variable might be something you want to know about.
The book iOS Recipes refers to this issue:
Cleanup in -dealloc
In addition to releasing all relevant instance variables in the -dealloc, our examples set them to nil. This practice is one of the most hotly debated topics among Cocoa programmers, and both sides of the argu- ment hold weight. This book is not meant to participate in the debate at all: we set them to nil, but that doesn’t mean you have to. If you don’t like nil-in-dealloc, feel free to leave it out of your own code.
A quick google search found this thread:
http://www.cocoabuilder.com/archive/cocoa/204055-why-should-we-set-ivars-to-nil-in-dealloc.html
Sometimes when one property becomes invalid (set to nil) we want to make other properties invalid too. If a class invalidates a property by using self.property_name=nil, then this will send a release message, which will cause a crash in dealloc if we have already called release on that property. If the invalidation occurs in a superclass, then this error is hidden and quite nasty. So whenever a superclass might invalidate a property it may be a good idea to set it to nil rather than just deallocing.

Memory Management Question in Objective C

I have a tableviewcontroller where I populate some data from a sqlite db and for each row, I download a file from a http server and cache it locally. I cache it only when the "detailsview" is opened. And the detailsview responds back to this table through a delegate after the file download is complete.
But, when this tableview itself is popped out of the navicontroller., the call to delegate fails with a EXEC_BAD_ACCESS
I called [_delegate retain] in the setDelegate of the details view and everything works fine, but I'm not sure whether this will leak memory...
Could anyone advise?
Your delegate is getting released prematurely, and sending a message to an invalid object will call EXEC_BAD_ACCESS. Retaining it will fix the problem, but in general it's good practice to not have an object retain its delegate, as there is the potential for retain cycles, so you might need to rethink your structure. If you're releasing your delegate when the view is dealloc'ed, you need to remove it unless you're also retaining the delegate in setDelegate:.
Generally, delegates are not retained to avoid retain cycles. If the delegate may be released before you, then it is the responsibility of the delegate to clear your reference before it is finished being deallocated (eg in its dealloc).
However, if any property is set to "retain" or "copy", then you would retain/copy it in the setter (or use #synthesized setters which will do it for you), and release it in dealloc to avoid leaking. As said above though, that may lead to a retain cycle so that neither object ever gets deallocated.
I would suggest you turn on some memory debugging with environment variables NSZombieEnabled and NSAutoreleaseFreedObjectCheckEnabled and see if it tells you which object is being over released.

Why are Objective-C delegates usually given the property assign instead of retain?

I'm surfing through the wonderful blog maintained by Scott Stevenson, and I'm trying to understand a fundamental Objective-C concept of assigning delegates the 'assign' property vs 'retain'. Note, the both are the same in a garbage collected environment. I'm mostly concerned with a non-GC based environment (eg: iPhone).
Directly from Scott's blog:
"The assign keyword will generate a setter which assigns the value to the instance variable directly, rather than copying or retaining it. This is best for primitive types like NSInteger and CGFloat, or objects you don't directly own, such as delegates."
What does it mean that you don't directly own the delegate object? I typically retain my delegates, because if I don't want them to go away into the abyss, retain will take care of that for me. I usually abstract UITableViewController away from its respective dataSource and delegate also. I also retain that particular object. I want to make sure it never goes away so my UITableView always has its delegate around.
Can someone further explain where/why I'm wrong, so I can understand this common paradigm in Objective-C 2.0 programming of using the assign property on delegates instead of retain?
Thanks!
The reason that you avoid retaining delegates is that you need to avoid a retain cycle:
A creates B
A sets itself as B's delegate
…
A is released by its owner
If B had retained A, A wouldn't be released, as B owns A, thus A's dealloc would never get called, causing both A and B to leak.
You shouldn't worry about A going away because it owns B and thus gets rid of it in dealloc.
Because the object sending the delegate messages does not own the delegate.
Many times, it's the other way around, as when a controller sets itself as the delegate of a view or window: the controller owns the view/window, so if the view/window owned its delegate, both objects would be owning each other. This, of course, is a retain cycle, similar to a leak with the same consequence (objects that should be dead remain alive).
Other times, the objects are peers: neither one owns the other, probably because they are both owned by the same third object.
Either way, the object with the delegate should not retain its delegate.
(There's at least one exception, by the way. I don't remember what it was, and I don't think there was a good reason for it.)
Addendum (added 2012-05-19): Under ARC, you should use weak instead of assign. Weak references get set to nil automatically when the object dies, eliminating the possibility that the delegating object will end up sending messages to the dead delegate.
If you're staying away from ARC for some reason, at least change assign properties that point to objects to unsafe_unretained, which make explicit that this is an unretained but non-zeroing reference to an object.
assign remains appropriate for non-object values under both ARC and MRC.
Note that when you have a delegate that's assign, it makes it very important to always set that delegate value to nil whenever the object is going to be deallocated - so an object should always be careful to nil out delegate references in dealloc if it has not done so elsewhere.
One of the reason behind that is to avoid retain cycles.
Just to avoid the scenario where A and B both object reference each other and none of them is released from memory.
Acutally assign is best for primitive types like NSInteger and CGFloat, or objects you don't directly own, such as delegates.