I have memory issues with my iOS app and I have several questions about that.
Firs of all, I'm working with iOS 6 and I'm using ARC.
Now let me explain my situation :
I have 2 views. From the first view, if I tap on a button, I create the second view (using alloc and init) and I display it as a modal using this code :
[self presentViewController:secondView animated:YES completion:^{
[secondView prepareToDraw]; // Function I use to start my computations and rendering
}];
At some time, when computations are finished I want to close my second view and go back to the first view. I' using this code from my second view :
[self dismissViewControllerAnimated:YES completion:^{
[self finished]; // Function I use to free some malloc
}];
I run my application with Instruments Allocations and Leaks and I have no Leaks.
Here is the code of my didReceiveMemoryWarning :
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
if ([self isViewLoaded] && ([[self view] window] == nil)) {
self.view = nil;
[self tearDownGL];
if ([EAGLContext currentContext] == self.context) {
[EAGLContext setCurrentContext:nil];
}
self.context = nil;
}
// Dispose of any resources that can be recreated.
NSLog(#"Resources freed");
}
The tearDownGL function frees OpenGLES resources like textures, vertex arrays, ...
When I run my application, after several switches between the first and second view I receive memory warnings and then my application crashes.
Here are my questions :
1- Is the application automatically freeing my UIImage, UIView, ... of my controllers? If not, how can I free them as I'm using ARC?
I also saw the viewDidUnload function but it's deprecated as the documentation says :
Called when the controller’s view is released from memory. (Deprecated
in iOS 6.0. Views are no longer purged under low-memory conditions and
so this method is never called.)
But if views are not purged anymore under low-memory conditions, how can I free more memory to prevent my application from crashing?
What should I do?
2- I put a breakpoint on the didReceiveMemoryWarning function for my 2 controllers. When I run the application on the simulator I simulate a memory warning.
I can see that the didReceiveMemoryWarning is called once for my 2 controllers.
But if I switch several times between my first and second controllers the didReceiveMemoryWarning is called once for my first view controller but is called several times for my second view controller. If I switched 3 times, the function will be called 3 times. So I guess, when I "close" my second view to go back to the first view, the second view is not freed and still exists. Why ? How can I force it to be destroyed ? (as I won't use it anymore and create a new one)
I create the second view controller in a function and I don't keep any reference to it (it is not stored in the class).
You should release (in ARC that means setting all strong references to nil) all memory (images, NSData objects, Arrays, all data represented by the model layer etc.) that are currently not required and can (easiyl) be re-created when they are used again. All of your other code should be written in a way that properties/iVars are checked for nil if those objects could have been released during a memory warning and then will be re-created.
I doubt that self.view is amongst that objects that might be disposal.
You may have displayed an UIImageView. That was probalby created with an UIImage object. You not not really need that UIImage in memory while the UIImageView is displayed. (If UIImageView still need it then it retains it or keeps a strong reference on its onw so that you don't have to worry about keeping the image itself.) THAT are the resources to be released.
If self.context is amongst the disposal resources, I cannot say. It may well be.
ARC does not always mean that the images, views ,etc gets released instantly. It gets added to the nearest arc pool and gets released.If the application may require it or uses it somewhere it gets added to the main pool which gets released only when the application terminates. So it is better to remove the object yourself if you think it has served it purpose. Especially in case of images it remains in the memory as it does not know whether it is getting used anywhere else or not.
Whenever you work with blocks, you should use a weak reference to self, since this can lead to retain cycles. So change your code to this:
__weak typeof(self) blockSelf = self;
[self dismissViewControllerAnimated:YES completion:^{
[blockSelf finished]; // Function I use to free some malloc
}];
Also, your code to free anything should be in dealloc. You don't need a custom method for it, if it only happens at the end of the lifetime of that controller.
Your first call also seems wrong:
[self presentViewController:secondView animated:YES completion:^{
[secondView prepareToDraw]; // Function I use to start my computations and rendering
}];
If prepareToDraw only happens once, when the controller is presented the first time, than you should run this code in viewDidLoad. This would also benefit your architecture, since only the controller itself should know what it has to setup in the beginning and to tearDown at the end.
Hope that helps. Perhaps you have other/more problems in your code.
Please have a look at auto-relase pools : AutoReleasePools
It reads :
Use Local Autorelease Pool Blocks to Reduce Peak Memory Footprint
Many programs create temporary objects that are autoreleased. These objects add to the program’s memory footprint until the end of the block. In many situations, allowing temporary objects to accumulate until the end of the current event-loop iteration does not result in excessive overhead; in some situations, however, you may create a large number of temporary objects that add substantially to memory footprint and that you want to dispose of more quickly. In these latter cases, you can create your own autorelease pool block. At the end of the block, the temporary objects are released, which typically results in their deallocation thereby reducing the program’s memory footprint
I had a similar issue, where I encapsulated all the big objets that I wanted to get rid of in an #autoreleasepool block.
Related
I can't seem to find any resolutions to this. I've made all my objects 'weak' in both view controllers in question. I have included dismiss functions and even the 'RemoveFromSuperView' function. I tried them all without luck. I also tried making the button action 'modal', 'push', ect. None made any difference.
Essentially as I move from controllers, memory seems to just accumulate more and more. On both controllers I'm simply using WebView's. I rack up over 100MB of memory usage after some time navigating between views. Eventually the app runs out of memory and crashes.
How do I either clear all memory accumulated by the app or properly dismiss/kill all inactive View Controllers and clear all memory associated?
This is how you override dealloc method
- (void)dealloc {
[_object release];
[super dealloc];
}
where _object is whatever property you initialized.
I have a class to enable placeholders for UITextView. This class is called PlaceHolder, and it has initializer that accepts view. It then stores it in strong property and sets itself as view delegate. I store array of PlaceHolders in my strong array in viewDidLoaded:
self.placeHolders = #[[[PlaceHolder alloc]initWithControl:self.textView andPlaceHolder:#"text"]];
I then call
-(void)viewWillUnload {
for(PlaceHolder* holder in self.placeHolders) {
[holder unload]; // This method does self.view = nil; in each PlaceHolder
}
self.placeHolders = nil;
}
Nice. But viewWillUload is deprecated! It says I should use lowMemoryWarning, but it does not means view is unloaded!
So, what is the correct place to remove my placeholders?
If you have easily recoverable (i.e. cacheable) large data that you wish to unload when there is low memory, then implement didReceiveMemoryWarning and UIApplicationDidEnterBackgroundNotification to set that data to nil, thus releasing it. Accompany this by "lazy loading", so that if you fetch the data and the data is nil, you reconstruct it. In this way, you are always holding on to the data only if there is no memory pressure (or danger of memory pressure in the background).
You can automate this to some by extent using NSCache, though personally I've never had occasion to do that.
I finally understood everything, thanks to apple docs and #matt book.
Since iOS 6.0 system never unloads views automatically because new devices have much more RAM. But if I want, I can unload it myself from didReceiveMemoryWarning by nilling by view which then will be created automatically on next access to view due to laziness. But first I need to make sure view is not displayed now. So, correct way is to do the following:
-(void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
if ([self.view window] == nil) {
// Low memory and our view is not displayed.
// We can unload view (if we want), and when controller will be displayed,
// system will call self.view, and it will call loadView and then viewdidLoaded
self.view = nil; // Unload view manually
// Do any cleanup.
}
}
I'm using Instruments to monitor my app's(ARC) memory usage, and found out that
When I pop a view controller from navigation view controller stack, its dealloc method is called.
But the memory usage only drops a little...(like 0.6M), and still much highter than before.
So here is the problem. The memory usage of my app keeps increasing....
How could I decrease the memory cost to the value before the view controller allocation.
Or at lease how could I release more memory.
Also, it seems that the memory cost is much highter when using xib(storyboard).
Should I set the data to nil like someArr = nil in dealloc method?
I have no idea. Anyone help please! Thank you!!
This image is captured when one view controller is allocated, and still alive after its dealloc method is called.......
You can try using #autoreleasepool{ } blocks, though be aware that the memory footprint doesn't necessarily return all the way to where it started. A big caveat is that if dealloc is already called, using autoreleasepool in your code might do nothing because the VC was already released properly.
Though you can consider where to use it within the view controller implementation, perhaps within a dealloc implementation for the VC. To ensure that when the VC's dealloc is called, objects that receive an autorelease within the #autoreleasepool block will be released immediately.
Snippet of mine from OSX code:
- (void) dealloc
{
#autoreleasepool {
// End KVO
[self stopObservingIndexPath];
for (NSView* subView in _treeSubViews)
[subView removeFromSuperview];
[_categoryView removeFromSuperview];
[self.view removeFromSuperview];
_treeSubViews = nil;
_categoryView = nil;
}
}
... that was written in a quest to reduce footprint like yours, by forcibly dismantling the view hierarchy.
And the Apple reference here.
In new iOS 6, viewDidUnload is deprecated and we have been instructed to use didReceiveMemoryWarning instead, to manage objects in UIViewController instances and subclasses. Is it equally effective to assign nils to UIView kinds inside didReceiveMemoryWarning like the way it has been done inside viewDidUnload?
I am asking this because these two methods seems to be working differently. It seems like didReceiveMemoryWarning doesn't guarantee viewDidLoad to be called again to re-instantiate any necessary UIViews.
I suspect with iOS 6, memory management is done without requiring to manually deallocate UIView. Please help me to know what I have missed in understanding the lifecycle of UIViewController.
My preferred method is now the following:
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
if (self.isViewLoaded && !self.view.window) {
self.view = nil;
}
// Do additional cleanup if necessary
}
Note that the test self.isViewLoaded is essential, as otherwise accessing the view causes it to load - even the WWDC videos tend to miss that.
If your other references to subviews are weak references, you don't have to nil them out here, otherwise you want to set them to nil, too.
You should get rid of viewDidUnload completely, and every code there should move to appropriate places. It wasn't guaranteed to be called prior to iOS 6 before anyway.
In the iOS reference for viewDidUnload:, it states that this is deprecated for iOS 6 because
Views are no longer purged under low-memory conditions and so this
method is never called
It doesn't say anything about placing this code in didReceiveMemoryWarning:. Since views are no longer purged under low memory conditions, you never have to worry about cleaning up your views in either method.
The answer by Eiko is not correct, and we should NOT set self.view to nil when receiving low memory warning. Doing so is useless and may be harmful.
iOS 6 will automatically freeing bitmaps of views which is not currently displayed, See http://thejoeconwayblog.wordpress.com/2012/10/04/view-controller-lifecycle-in-ios-6/ for details.
I had some memory problems due to Xcode's template for a UIPageViewController caching all the page data, so I changed it to load the pages dynamically, so now when my app receives a low memory warning, it releases the memory for page's not showing, but if the user is flipping through the pages real fast by tapping the edge of the screen, it still crashes. I'm guessing this is because it can't free the memory fast enough when didReceiveMemoryWarning gets called. If the user is flipping slowly, it works fine. I limited the speed at which the user can flip pages, but it still happens. I want to be able to free up the memory every time the page is turned, and not have to wait for a low memory warning. I'm using ARC. Is there a way to do this? Or what else can I do to prevent this? Thanks.
EDIT:
(UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController
{
NSUInteger index = [self indexOfViewController:(SinglePageViewControllerSuperclass *)viewController];
if ((index == 0) || (index == NSNotFound)) {
return nil;
}
index--;
return [self viewControllerAtIndex:index];
}
(UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController
{
NSUInteger index = [self indexOfViewController:(SinglePageViewControllerSuperclass *)viewController];
if (index == NSNotFound || index == MAX_PAGE_INDEX) {
return nil;
}
return [self viewControllerAtIndex:++index];
}
I think you hypothesis is correct, since I also experienced a similar behavior: when you flip to the next page, also for the sake of animating things nicely, the new page is allocated before the old one is deallocated and it takes some times for the old one to be deallocated. So, when you flip fast enough, objects are allocated faster than they are deallocated and eventually (actually, pretty soon), your app is killed due to memory usage. The deallocation delay when flipping pages becomes pretty obvious if you follow the allocation/deallocation of memory in Instruments.
You have three approaches to this, IMO:
implement a "light" viewDidLoad method (actually, the whole initialization/initial display sequence): in some app, it makes sense, e.g., to load a low resolution image instead of the high resolution image that will be displayed; or, slightly delaying the allocation of additional resources your page need (db access, sound, etc.);
use a pool of pages, say an array of three pages (or 5, it depends on your app), that you keep "reusing" so that the memory profile of your app remains stable and avoid spikes;
careful review the way you allocate and release memory; in this sense, you often read that autorelease add some "inertia" to the release/deallocation mechanism, and this is pretty easy to understand: if you have an autoreleased object, it will be released by its release pool only when you cycle through the main loop (this is true for the main release pool); so, if you have a long sequence of methods that are called when flipping page, this will make the release/dealloc happen later.
There is no magical bullet when it comes to memory usage optimization, it's a pretty detailed and hard work, but IME you will be able to reduce the memory profile of your app if you review your code and apply those 3 guidelines. Especially, inspecting the spikes of memory allocation in Instruments and trying to understand to what they relate is extremely powerful.
Here is an additional change I made, which someone might find helpful:
Basically, I only allow a new page turn to begin if the previous one has finished.
I'm using apple's default PageViewController project as a template so I'll use terms defined in that project.
Whenever a page VC is requested through viewControllerAtIndex:, I set a boolean value on ModelController called 'shouldDenyVC' to YES.
In my EbookViewController which is the UIPageViewController's delegate, I capture the gesture recognizers, and assign EbookViewController as their delegate:
self.view.gestureRecognizers = self.pageViewController.gestureRecognizers;
for (UIGestureRecognizer *gr in self.view.gestureRecognizers) {
gr.delegate = self;
}
Then, I'm able to deny a page turn by denying the gesture recognizers:
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch: (UITouch *)touch
{
if (_modelController.shouldDenyPageTurn == YES) {
return FALSE;
}
return TRUE;
}
And finally, I set _modelController.shouldDenyPageTurn = NO at the end of the UIPageViewController delegate method pageViewController:didFinishAnimating:previousViewControllers:transitionCompleted:
I also had to set _modelController.shouldDenyPageTurn = NO at the end of any preloading so that page turns are allowed off the bat.
There is a bug in iOS5 at the moment that causes a scroll view to leak a small amount of memory.
Have you tried profiling your application in instruments checking for allocations and memory leaks?
You can simulate a low memory warning either in the simulator (hardware -> simulate low memory warning). Or you can do it via code, (just remember to remove after debugging because this will get your app rejected!)
[[UIApplication sharedApplication] performSelector:#selector(_performMemoryWarning)];
If you are using strong or retain properties then set them to nil after you are done with them and ARC will release the memory they are pointing to behind the scenes.
If you are creating lots of temporary objects (objects that are not properties or not alloc'd) then insert an autorelease pool:
#autoreleasepool {
}
And finally, show some code and we can better help you.
It might be caused by Rendering. When flipper too fast, the memory and CPU used by redrawing the "Page" will increase rapidly. If the views you used in UIPageViewController is based on CALayer and have too many pages, flipping too fast will definitely crash the App.
One solution is to customize the layer and cache the rendering result. Re-render the content only when must. But the cache might increase memory usage.
Since you didn't post any code it's hard to guess where exactly lies your problem.
To force unloading a view you can override viewDidDisappear: method of those viewcontroller classes that are appearing in UIPageViewController.
Code would look like:
- (void)viewDidDisappear:(BOOL)animated {
[self didReceiveMemoryWarning];
}
If you also have didReceiveMemoryWarning overriden don't forget to call [super didReceiveMemoryWarning]; from it.
There can also be some confusion on how UIPageViewControllerDataSource methods work - you might have some 'mixed wires there'. Check accepted answer here.