Which memory is released by didReceiveMemoryWarning/viewDidUnload? - iphone

My iPhone application is running into problems when deployed to the device, principally because I haven't handled memory warnings thus far (no problem in the simulator, with 4GB of ram on my dev machine!). No problem there, I just need to handle these warnings more skilfully (less suckily...).
Question is, which memory does the runtime release... just the view and subviews? I suspect that it is just these, but want to be sure that the runtime will not dereference any of the objects or memory in my controller (ie. not in the view).
Subquestion: if it is just the view and subviews, do I need to do anything special in viewDidLoad to make sure that when the view is brought back into memory the view shows correct data, or is it all handled automatically via my IBOutlet-s?

There are potentially many things that the view, or its subviews, may cache - such as image data. These are the sort of things that will be purged.
Anything specific to your application that you can afford to flush you'll need to do yourself by handling that callback.
However, this may be more of an indication that you are either leaking memory or not being as efficient with it as you might be. It's certainly worth running the app in Instruments with the Leaks tool, as well as running with the CLANG compiler's static code analyser. Also, examine your code to see if you are holding on to blocks of memory you don't really need - whether you can compress images more etc.
Remember, before the 3GS or the latest iPod touch, system memory was 128Mb but you should only count on having about 25-30Mb available to your application

Neither viewDidUnload nor didRecieveMemoryWarning automatically release anything. You need to override both of these methods.
Generally, viewDidUnload should release anything in the view that wasn't created in IB, and that you can reasonably deal with reloading when the view is loaded up again.
And didRecieveMemoryWarning is a message that is sent to your app when the system is running low on memory. When your app receives this message, you should release anything and everything that you don't immediately need, or risk the system forcibly shutting down your app.

Related

Memory crashes in iOS with real memory usage only at 5megs

I have been hunting down memory leaks for some time in my app. As of right now, as I flip back and forth between two views while watching the memory monitor instrument, the real memory fluctuates between 5 and 6 megs. This is all fine -- as far as I can tell everything is getting released properly when I pop back off a view. However, the virtual memory continues to increase and my available real memory drops rapidly every time I push the view back onto the view stack (even though the real memory usage of the app isn't increasing). Eventually, this all leads to an out of memory crash. Is this a telltale sign of any specific issue, or am I just missing a memory leak somewhere?
EDIT: The odd part is, I get an out of memory crash while the app is still only using up about 5 megs of real memory.
Do not use -retainCount.
The absolute retain count of an object is meaningless. It is an implementation detail. It may be influenced by many factors well beyond your code.
You should call release exactly same number of times that you caused the object to be retained. No less (unless you like leaks) and, certainly, no more (unless you like crashes).
See the Memory Management Guidelines for full details.
In this specific case, you are leaking memory but in a way that leaks can't find it. The objects that are leaked are still connected to your overall application's object graph somehow. Maybe through a notification, maybe through delegation, doesn't matter -- leaks sees the reference and concludes that the object might still be live.
Use the Allocations Instrument. Configure it to only track live allocations (since you don't care about objects that have been deallocated). Do some stuff with your app. Check out what Allocations knows about and explain why all those objects should stick around. You can use the data mining facilities to filter down to just your objects.
Anyway, you can also use the "Build -> Build and analyze" option to find suspicious non-conventional code.
Another reason why you may have memory lost in lower API layers is if you don't remove all your views from your view hierarchy (aka : not calling [view removeFromSuperview] everywhere). At least that's what seemed to have happened to me.
Note that most of time this isn't required, as you would simply release the main view and all its subviews, then rebuild it from the view controller when needed. Things start to get more tricky when you're not releasing the whole hierarchy but instead simply remove some of them from the hierarchy.
In that case, I came to the conclusion that you may have buffers or layers still cached in lower API parts, and in that case your Allocation instrument won't help you.
In order to monitor correctly you'll need to use the "Memory Monitor" (in System). You'll see that the "Physical Memory Free" line dropping close to 0 is the most reliable indicator that a Memory Warning will be issued.
Another advantage of using this instrument, is that you can attach it to a running process, thus making it possible to have console output and instrument running together easily.
Circular references also won't be counted in Leaks but you can track those in Allocations. Best bet is to fire up Allocations and get to a state where you think everything should be gone (or certain objects should be). If they're hanging around go dive in to them and look at where they've been retained and sort out the proper memory ownership/releasing.
As for Allocations, there are some things that it doesn't track that can affect the overall memory. Some of the things include some CGImage backing stores, some CoreAnimation stuff and some database stuff.
Have you used the "Leaks" Performance Tool? And check out the logs in Organizer to see if there's anything there.
Also look into the dealloc for the view controllers and make sure you are properly releasing all of it's objects?

IPhone memory problems

I am working on an App that is already been made but Memory Management was not considered in the development stages.
So what can I do to keep the App memory usage low as soon as I get a memory warning?
Is there any general tool or some piece of code that I can use to release any unused memory?
Two things.
First, if you're using any sort of view hierarchy (tab bar, UINavigationController, or something you've rolled on your own), the message is going to propagate upward. That means one handler for memory messages in your root-level UIViewController subclass can handle memory events for the whole app, which is very handy.
Second, you want to go after the low-hanging fruit. In the app I'm currently working on I have a couple different arrays of dictionaries that contain my app data, and each of those dicts contains both a thumbnail and a larger image. Obviously those make up the bulk of the bits I'm keeping in memory. So the first thing my root view controller does when it gets a memory warning is go through those data sets and set those images to nil. Because they're retained properties, they get released when the setter is called and the images are freed from memory. Then I have functions in my view controllers to notice the nil-ness of those image fields and reload them from the server.
By the way (okay... two things and a "by-the-way"), memory warnings aren't a problem. Some people seem to feel bad about getting them, want to redesign everything about their app so they never get one. That's really not necessary; even the best-designed app will get warned about memory occasionally, just because of the unpredictability of the background apps on the device. The important thing is to handle them well.
Xcode can be combined with the Instruments tool to show you the places where your application is leaking memory, i.e. where reserved memory is not released properly. CIMGF has a solid tutorial on this: http://www.cimgf.com/2008/04/02/cocoa-tutorial-fixing-memory-leaks-with-instruments/
You should have a look at the method
- (void)didReceiveMemoryWarning
of your UIViewControllers. This method is called when you receive a memory warning. Here you can release objects currently not used. But it's your part to determine what is used and what not.
The "Build and Analyze" feature of XCode is a tool you could use to see if the code contains any obvious memory leaks.
You should have a look at the small section "Memory Management" in the UIViewController class reference:
http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html
Also an important document is the "Memory Management Programming Guide":
http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html

Memory usage accounting in a navigation controller-based app;

I have a navigation controller-based application that could be active for a relatively long time and can load multiple screens, revisiting some in the course of its life - a business application. When I push a screen I allocate some memory; when I go back (pop it) I need to ensure memory is not lost.
Now in Leaks I have a clean slate. No memory leaked, not so hard to do with the 10.6 static analysis feature and confirmed using instruments. Checking manually, I am sure I am releasing everything allocated in viewWillAppear in viewWillDisappear; everything allocated in viewDidLoad in viewDidUnload; everything allocated otherwise in dealloc.
I have used NSZombiesEnabled in development but I definitely do not have it active now.
When running under Object Allocation however I see memory usage growing. On entering a new view I see memory increasing but not decreasing by the same amount when navigating back. Nor is this simply the system failing to deallocate immediately, when left for some time memory remains static. This behavior is seen on every view.
What techniques can I use to isolate this memory? Should I be aiming for the application returning to some baseline after every view? How can I isolate reporting of memory used by subsystems such as Core Data, where I rely on faulting to load objects and should not be trying to manipulate them explicitly, and the code over which I have full control?
It is natural that the navigation controllers memory footprint grows as you push views to it.
If you are using Core Data anyways you could persist the state of the entire application to Core Data each time you push or pop a view. This way nothing will be lost.
The navigationController manages the memory for the viewControllers, so if you exceeds the iPhones memory it will then start deallocating the viewControllers. Core Data manages memory pretty aggressive so it is a good way to go.
By this approach I think you will utilize the memory management of the framework instead of trying to roll your own and potentially introducing long terms memory bugs:)
I would go for something like an Entity per viewController, and an Entity that saves the context in which the were loaded. This way you could just test to see if the framework has deallocated any of your viewController and then restore the navigationController stack if it did.
Hope this was at least something to consider:)

Memory behavior of / Possible memory leak in UITableView

I am profiling my iPhone application with the 'Activity Monitor' Instrument. When I use UITableViews and scroll through them, I see the memory usage of my application go up all the time while I scroll. When I return to the previous view and the UITableViewController gets deallocated, the memory usage goes down a bit, but not to where it was previously. But the 'Leaks' instrument does not find any memory leaks, and neither does the static analyzer find some. I also ensured that there are never more than 12 UITableViewCells allocated at any time, so those are re-used properly (the Cells are also created with an appropriate autorelease so they will be de-allocated when unused). I'm also pretty sure that I don't have any memory leaks built into the code of the corresponding UITableViewController.
Is this normal behavior, e.g. will the application release the memory it has claimed at a later time, maybe when it is needed somewhere else?
Cheers and thanks in advance
MrMage
Do you have NSZombieEnabled? I've seen this cause "incorrect" results in Instruments memory profiling since those instances will hang around.

What kind of odd behavior can occur during a memory leak on the iPhone?

I've been able to replicate a bug consistently on an iPhone app I'm working on. The bug always follows as soon as my UIViewController's didReceiveMemoryWarning method gets invoked. Some of the issues I'm seeing are as follows:
UITextField's text property niling out.
The previous data in the UITextField is getting appended to a string multiple times, thus giving me corrupted data back when I HTTP to the server
This happens as soon as my breakpoint on didReceiveMemoryWarning hits, otherwise all appears to be working just excellent. My question is, does it sound normal for this odd behavior to occur during a memory leak? If so, what is happening with the UIViewController that's causing such ad-hoc duplication of data in a previous UITextField (which is a part of a UITableViewCell's contentView, so I figure there's some oddity going on with dequeueing of the cell)
It's interesting none the less.
Thanks!
When the iPhone runs low on memory the OS tries to intelligently do things to reduce memory overhead. In a few cases I've seen this cause odd behavior such as text content go missing or a keyboard failing to display.
However you may want to focus on finding the source of your memory problems instead of the results.
Usually, not very much, as long as your application is not using all the memory in the hardware. But memory leaks can stack up, and next thing you know you are out of physical RAM. You may see a sudden performance dip as virtual memory kicks in and parts of your app starting paging to the much slower flash disk storage. This is when your controller will likely get a low memory warning, and UIKit may remove some things it thinks you don't need (like views without superviews, possibly other thigns). Soon after that, the entire app will crash as the iPhone OS forces it to quit because it is using too much memory.
The short version: memory leaks lead to crashes. But the removal of object it thinks you dont need may cause some odd behavior as well.