Cocos2D project with many scenes does not release memory properly - memory

I've got a great problem and I don't understand very well why occurs. This is the case:
Have a great project in Cocos2D with 10 scenes. Each scenes is a page of a book with huge sprites. It uses Kobold2D 1.0.2 implementation.
Every page has common objects in a singleton class, to put a common menus via LayerColor.
The sprites is TexturePacker in PVR.CCZ RGBA4444 and in iPad memory
are around 16-20Mb every spritesheet loaded.
I use CCTransitionTurnPage for replaceScene for one to the next one.
At init method of each page (class), load the texture and FrameFile.
At onExit method of each page (class), unload the textures and frameFile. I used the dumpCachedTextureInfo and says me textures load and unload from memory perfectly.
Of course, I remove from child all objects. All my sprites are common variables declared on the interface section at .h, because I need to access them in every method of the class.
My project is made with Kobold2D integration in a ARC project (but you know the attached Kobold2D project has ARC not enabled for compatibility problem)
The fact is when I start the project, everything seems perfect but memory is increasing for every scenes (page) I made. Page1: 30Mb., Page2: 40, Page 3: 54, Page 4: 65... After 7 or 8 scenes, Instruments, Xcode or the iPad itself hangs the application without any message (except Instruments with a final Low memory Warning).
Why there's no memory releasing after each scenes? Maybe it's because ARC and the no super dealloc variable. Why textures appears unload perfectly but seems like there's no unload because memory is growing without control until crash?

I was having a similar problem with memory retention and no leaks showing up in instruments. I couldn't get -(void) dealloc to even get called until I wrote the following into every scene's .m file:
-(void) onExit {
//unschedule selectors to get dealloc to fire off
[self unscheduleAllSelectors];
//remove all textures to free up additional memory. Textures get retained even if the sprite gets released and it doesn't show as a leak. This was my big memory saver
[[CCTextureCache sharedTextureCache] removeAllTextures];
[super onExit];
}
After implementing this, my memory was released after every replaceScene: was called. Hope this is of some use to you.

After months of working, I learned the most important lesson on Cocos2D. The retain increase by one when you put any CCNode object on a CCArray or NSArray or NSDictionary... This means you must release the objects from this objects before the CCLayer or CCScene dealloc.
You must put a [array removeAllObjects] or [dictionary release] on the - (void) cleanup and after all your objects has removed, then put a [super cleanup];
In the meantime, on - (void) onExit you must remove all scheduler from the instance. Not only a scheduler itself. Remember to stopAllActions on any CCNode. But, carefully, because stoping actions from CCNodes (Sprites or something) must be on cleanup, before any removeAllObjects.
And remember: if CCLayer or CCScene does not remove properly, SimpleAudioEngine not will release the audio too.

Related

How can you remove a CCNode from a scene and make sure it is released from memory? Cocos2d V3

I have a scene where I add the node 'page';
[self addChild:_page z:-1];
'page' is initialized in the header file as
#property CCNode* page;
When I remove the page from the scene
[self removeChild:_page];
the memory remains the same (as seen through the debug navigator).
This is a problem because I add and remove many pages that contain hd images, animations, and physics environments. I receive low memory warnings after adding and removing several nodes, and the app will crash.
Below is the code that removed most of the content of the CCNode from memory. Note the node did not contain audio.
At the top of your implementation file add the following line.
#import "CCTextureCache.h"
In your implementation file also add an onExit method.
-(void)onExit{
[super onExit];
[self removeAllChildren];
[[CCTextureCache sharedTextureCache]removeUnusedTextures];
}
To make sure that textures were removed you can use
[[CCTextureCache sharedTextureCache]dumpCachedTextureInfo];
Use the debug navigator in Xcode to monitor your memory in real time running an app.
Other research on adding/removing nodes:
In cocos2d V3.x you "don't have to worry" about memory because once your app reaches a certain memory threshold for a device, and you get the 'low memory warning', CCAppDelegate will automatically purge cached data.
// purge memory
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
[[CCDirector sharedDirector] purgeCachedData];
}
However, in a case where you load big, sometimes, multiple texture files and there might be a chance of the app exceeding the memory threshold, keeping memory low can be beneficial.
Removing unused data might also help remove code that might have potential memory leaks or bugs that can affect your program.

How to find the real cause of memory warning and how to resolve in iOS app

I have go through many posts related memory management, ARC , memory management techniques like autoreleasepool and using instruments tool to detect which code is causing memory warning but in my case I am not able to figure out the exact cause.
Basic details which you must know about the app:
We have developed an iPad app. In that we have to use more then 2000 images in some case, so when my app launch we do not want to show them placeholder image (client requirement).so to achieve this, we used SDWebImage , store images on disk and later than we are loading images from there.
There are so many core animation I have performed like "Gennie effect", display pop-up and so many other core animations.
We have used ARC in our project and we found that due to memory warning app is crashing randomly.
We have used Instruments "Allocation" for finding the dirty memory.
Previously we analyze the logs and we stored images with SDWebImage in DISK, it resolve that frequently crashing of app, but still app is crashing due to memory warning.
When we go deep in that we found "Anonymous VM" is keep incrasing and not releasing memory when any screen switch in iPad.
Here is the screenshot of profiling of our app on device.
Anyone please suggest tips or coding techniques or any idea by which We can reduce memory load and resolve memory warning.
Any help will be appreciated. Thanks.
In WWDC 2012 Session 242 iOS App Performance: Memory,Apple introduce a way to detect memory problem with Allocations template of Instruments,start from 31 minutes.
1.
Apple suggests push pop repeatedly before take a snapshot of the heap,I prefer push pop just once.
The Snapshot button is Named "Mark Generation"
You should take Snapshot multiple times.
2.
If your memory grow between each Snapshot,You can dig into one of the snapshot except the first one.
Sort the objects by Persitent,you probably has seen your problem ViewController (if you only push pop once).Or you can just search for it.
3.Now you can dig into the call tree ,find and fix the problems.
4.You can use this technique not just for push pop viewControllers,but also scrolling in a tableView ,perform a databaseSearch and any other cases.
Wolverine,
Not saying this is an absolute answer to your question, but might provide you some hint to resolve the problem.
My Case :
Today morning while debugging the memory crash just as your's in one of my chat application I came accross a similar scenario. I am using SDWebImage as well to cache and load the images for the subsequent usages.
Initial observations made me believe that it is the crash because of SDWebImage. Soon I realized that crach was rather because of a very simple issue.
I had never tested whether my viewController's dealloc is getting called or not. On putting a breakpoint in dealloc I realized dealloc was never being called (for various reasons which I resolved now).
As in your case, my chatViewController though not loading 100's of images used to load 8 - 10 images at a time and crash started appearing when I used panorama images rather then normal Images.
Conclusion :
My viewController had strong reference to UIImageView which was loading heavy images and as dealloc was never called for my ViewController all the loaded images were never realesed which resulted in memory crash.
As I was loading heavy images I was performing several calculations to reduce the size of image. Most of the calculations involved repeated creation of image from NSData using UIImageJPEGRepresentation. Repeated allocation of data and image holder variable added to memory consumption of the app.
As my ViewController involved number of API calls, I had created a singleton reference service class to which I used to pass complitionblocks and unknwingly I had used self inside the completionblocks passed to the methods. Which actually contributed to ARC reference count increment and never let my view controller to get deallocate.
Way to Debug
As you have already mentioned in your question that you are loading loads of images in your ViewController make sure the viewController gets deallocated properly and releases all the memory loaded by all the ImageView's present in ViewController.
If your ViewController's dealloc is not getting called then as just a way to test (remember not a solution) in viewWillAppear set all the imageView's image property to nil and forcefully clear the memory loaded.
If ViewController dealloc not getting called turns out to be the culprit, try finding where you are sending self as strong reference. If found try using weak self.
I know its not a absolute answer to your question. Just sharing my experience with you. Hope this will atleast give you hint to solve yours.
Try Infer it may helpfull, it reports memory leak problems in iOS and C code.
A static analyzer in deployment at Facebook, where it is used as part of the development process for mobile apps. Infer targets critical bugs such as null pointer exceptions, resource leaks and memory leaks — problems which lead to crashes or performance degradation in apps.
It looks like some object in your app is not being released, probably due to a retain cycle. Check all references to delegates are weak references.
Also check blocks and ensure a strong reference to self is not captured in a block. If Object A keeps a strong reference to Object B, then passes a block containing a strong reference to self to object B, both objects are potentially locked in a retain cycle.
Use this syntax to pass a weak reference to self:
__weak typeof(self)weakSelf = self;
[doSomethingWithBlock:^() {
__strong typeof(weakSelf)strongSelf = weakSelf;
if (!strongSelf) {
return;
}
[strongSelf doSomething];}];
in Swift do this:
someObject.doSomething() { [weak self] in
self?.doSomething()
}
or use [unowned self] - both create a weak reference to self, in the case of [weak self], self is optional
To ensure all your objects are deallocated as expected, put a log statement in your dealloc / deinit functions and check they are really being called.

CCTimer being leaked in cocos2d-iphone 1.0.1 using scheduled selectors

I'm now looking for memory leaks in my cocos2d-iphone 1.0.1 game using the Leaks instrument.
So far so good, I've fixed several problems. But there is one object being leaked that I can't quite understand:
It is a CCTimer object. The line that leads to this leak is
// This method is called when you encounter a random battle.
-(void)transitionToBattle {
[self unschedule:#selector(transitionToBattle)];
// Displays a "loading" screen
[self schedule:#selector(battleLoading)interval:0.5];
// Enters actual battle scene
[self schedule:#selector(enterBattle) interval:0.8]; // <--- Leak here
}
Not sure if relevant, but the enterBattle method is
-(void)enterBattle {
[self unschedule:#selector(enterBattle)];
glColor4f(1, 1, 1, 1);
[[CCDirector sharedDirector]pushScene:[BattleScene scene]];
}
battleLoading merely displays a sprite over the screen:
-(void)battleLoading {
[self unschedule:#selector(battleLoading)];
// The scene itself is running a CCRotateBy action, so I'll stop it
[self stopAllActions];
// << Create CCSprite for "now loading" here >>
// It is possible for the scene to be rotated, so let's fix that
self.rotation = 0.0;
// Make sure that the rotation fix is noticed
[[CCDirector sharedDirector]drawScene];
}
I understand that cocos2d uses a CCTimer to control scheduled selectors. However, I don't have the faintest idea on how could it possibly be leaking a CCTimer.
The code where these methods are located is quite large, but I'm certain that the snippets above are the only parts referencing enterBattle.
I can notice the leak once you are already in the battle scene, so it doesn't happen when you exit it. The leak doesn't occur always, just often.
I can see that the details above are not quite accurate, making it hard to pinpoint the problem. So instead I'd like to know if there is a reasonable way to debug a leaked CCTimer because of a schedule. What could possibly cause this?
And it seems to happen only with this specific schedule. I have lots of other ones and none seem to leak like this.
It seems like the culprit was this:
[[CCDirector sharedDirector]drawScene];
In my battleLoading method.
I don't really know why. I just removed it and so far I haven't seen the leak again.
Taking a look at this method for CCDirectorIOS, it seems to do something related to the scheduler. Maybe it isn't quite friendly with schedules, specially when you're changing scenes or something.

Memory Issue with ARC

I've used ARC to build a fairly simple application. However, I'm running into a memory deficiency, but I can't figure out what is causing it. Since I can't clarify what is causing it, I have a few specific details and questions.
The problem ensues when I try to load a new View Controller. This view controller hosts a number of images and, when loaded, will add a 3-4 minute audio file to an AVAudioPlayer in a singleton class I have.
The problem occurs when the view controller is pushed and popped 8-10 times. When the view controller is popped, I call stop on the AVAudioPlayer and return all relevant objects (including the AVAudioPlayer instance) back to nil.
I don't really understand what could be causing the memory leak, or what else could be ravaging the device memory, but I do have a few specific questions.
When stopping the AVAudioPlayer, will that still allow for a proper release in the memory?
Will setting the AVAudioPlayer pointer to nil after calling stop prevent the system from releasing certain data from the device memory?
Shouldn't anything, in ARC, be released when the owner(s) are deallocated (I'm asking about all of the views and data in my UIViewController that gets popped off the stack)?
Are there any issues with AVFoundation or AVAudioPlayer in ARC that I should know?
Is calling stop the wrong way to end an audio session / have it be released?
EDIT: I have started using the instruments tool in order to track my allocations and leaks. There aren't any memory leaks, or so the tool says, but the application will crash, nearly regardless of the live bytes. The application will crash when the total RAM used is over 200MB (210-230MB - my device has 256MB of RAM). My new question is will the total bytes allocated (even if they're not live) affect the memory crashes? If so, how can I prevent this?
Here is an image of a run that crashed. You can see the clump of memory warnings at the end.
Q) The problem occurs when the view controller is pushed and popped 8-10 times. When the view controller is popped, I call stop on the AVAudioPlayer and return all relevant objects (including the AVAudioPlayer instance) back to nil.
A) Add a dealloc method and log the dealloc, so you know nothing is retaining those, then look for these in the console:
- (void)dealloc
{
NSLog(#"MySpecialViewController getting dealloced!");
}
if you don't see these something is retaining this object - a delegate possibly.
Q) I don't really understand what could be causing the memory leak, or what else could be ravaging the device memory, but I do have a few specific questions.
A) You should be using ObjectAlloc in Instruments (and Leaks). These are really easy to use - run the project with them in the Simulator, just use the defaults, and you'll get a lot of good info right away. You can see WHAT is leaking which should really help.
Q) When stopping the AVAudioPlayer, will that still allow for a proper release in the memory?
A) No. You have to set your strong ivar/property to nil (which you said you are doing). I just checked and the AVAudioPlayer does not retain the delegate. That said, as a general rule, when I am shutting down anything its:
[something stop/cancel/etc];
something.delegate = nil;
something = nil;
Will setting the AVAudioPlayer pointer to nil after calling stop prevent the system from releasing certain data from the device memory?
Q) Shouldn't anything, in ARC, be released when the owner(s) are deallocated (I'm asking about all of the views and data in my UIViewController that gets popped off the stack)?
A) If the only thing that is retaining the ViewController, for instance the navigationController's viewControllers array, then yes, your viewController subclass should get dealloced, and all strong properties and ivars will too.
Q) Are there any issues with AVFoundation or AVAudioPlayer in ARC that I should know?
A) I know of none, and since this is a popular class expect your problem is in your code.
Q) Is calling stop the wrong way to end an audio session / have it be released?
A) If it were me:
[avPlayer stop];
avPlayer.delegate = nil;
avPlayer = nil;
EDIT: If you are getting memory warnings when your app is running, you are leaking or consuming some huge amounts of memory. Put a breakpoint where you get this warning, stop your app, and look at your allocations. I've never gotten a memory warning for real (I use ARC exclusively)
One area where it is easy to run into memory trouble while using ARC is situations where you are interacting with a Cocoa Touch API that requires the main thread from a background thread.
It doesn't sound like you are up against this, but if you start seeing inconsistent behavior (e.g. what appear to be random crashes, objects going out of scope prematurely, etc.) it is worth investing some effort to see if you are interacting with Cocoa Touch from a background thread.
Sometimes callbacks from Cocoa Touch (that one might assume would be on the main thread) aren't (we have seen this in some Game Center API's).

Invisible memory leaks... iOS 4

So I've got an issue with memory. It seems that I am not properly releasing or deallocating objects because I am getting this subtle buildup of memory in my game.
I init all objects like this:
self = [super init];
if (self != nil) {
//inititalize object
}
I release all objects in the dealloc methods like so:
[object release], object = nil;
Now I feel I should mention that my game runs on views. I have the main view that loads the sub-views into one variable called 'currentView'. I switch between the views like so.
if (currentView != nil) {
[currentView dealloc];
}
currentView = [[newView alloc] initWithVariables:vars];
I want to know if the issue is with my initialization and deallocation of objects or if its the views. I also want to know any strategies I can use to track down any leaks that don't show up in instruments.
I need this information ASAP, and if you can help it would be REALLY appreciated. Thanks.
EDIT: When I run it through instruments it shows the memory my app uses. and it has a strange pattern. When it loads the first view it starts with approx. 17mb used. Then I switch to the second view and it goes up to 22mb. Now if I go back to the first view it DOESN'T go down to 17mb again but down to about 20mb instead. Now when I continue to switch between the two it goes between 22mb and 20mb and stays pretty much the same. How can this be explained?
EDIT2: The pattern explained in the above edit is consistent throughout the entire game. Because of this consistency I've noticed a 70kb per-level leak in my game. Obviously this should not cause any problems while my game stays under 100mb so unless they play my game for EXTENDED periods of time, this shouldn't be a problem.
Although, I would still like to know how I can track down that 70kb leak.
You should be using release instead of dealloc. Every call to alloc should be matched with a release or autorelease; in your case, release because you want to control when it's freed.

Resources