How to remove level 1 from memory when replaying it? - swift

I am programming a game using scenekit that has different levels, that are different files (uiviewcontrollers) (level1.swift, level2.swift...) When you complete a level, you can replay it. What i have noticed, is when you start the game, it uses about 33 mb memory. Now when you press a replay button which presents the level 1 viewcontroller again, the game uses about 60 mb of memory.
So the question is, Is there a way i could somehow remove the level 1 when i present it again? Something like:
Level1. RemoveFromMemory
Self.presentViewController(level1)?

Those sounds like symptoms of a memory leak. You could cause this by keeping multiple strong references to the scene assets. You could also cause it by writing a retain cycle: parts of the scene hold strong references to each other, so even when you release the scene it can't let itself be deallocated.
Run your game using the Leaks Instrument. The WWDC videos on Instruments are helpful. And the Memory Graph Debugger in Xcode 8 will help you a ton.

Related

scene transition causes memory leak

I'm making a simple game using Xcode 10.1 IDE and swift 4.2
I've designed the main menu system so that each pages UI is presented through a separate scene.
Each time a new scene is loaded I get approximately 0.1 MB increase in memory usage. Not much but I don't want to start scaling the game with this issue.
Memory leak when presenting SpriteKit scenes
Memory problems when switching between scenes SpriteKit
Tab-based SpriteKit Apps and Scene Caching
I've had a good look through reference material and online. I've checked for Retain Cycles, through the following: Inserted deinit statements at the end of all scenes and object classes used. They are all called correctly. Profiled the app to look looking for zombie objects and leaks, with nothing obvious shown in the profiler results when running.
Does anyone have any idea to what causes memory leaks or caching on scene transitions and ways to prevent this?
I'm stumped scaling the game now seems like the wrong thing to do as the issue will probably compound as complexity increases.
After further testing I found the issue is with attaching sound actions through scene editor.
Attaching the actions through code gives stable memory use, with no increase of 0.1MB through scene transition.
Its only a partial answer but if any one else comes across this and has further info please post

new in using XCode Instruments to interpret memory warning for iPhone development, guidance needed

I am working on an iPhone game which receives memory warning that I am not experienced enough to interpret. I have been watching some iTunesU tutorial but I am still not very good at this..
I have received various memory leaks whilst running my game and I wanted to understand how to interpret the stack trace show in Instruments properly.
I attach a screenshot of the ObjectAllocation instrument output . Even when I zoom filter I don't manage to filter the data in the ObjectSummary .
The peaks in memory usage in 1 happen when the GameScene is initialized and all the data is loaded (ParallaxBackground, CCSpriteBatchNode) and Sprites and bullets frames are created (in an CCArray of spriteFrames).
The big blue peak is just at load time but the app freezes and then crashes only after a while and from the graph I see that the memory usage (blue bar) has gone down.. so I don't quiet get that. Also, whenver I try to use the leaks instrument the App crashes..
I know is a very silly question for someone experienced, but I just need some extra help getting started with this toolset.
I think the memory problem are due to the sprites I allocate in sprite cache classes, but I am not sure on this and hence wanted to investigate this using Instruments but can't find out how to see what is the object causing the memory warning and how to access the stack trace..
PS: I am running on an iPod 4th generatio and I am using Cocos2D as library
EDIT: I do not also understand why if the Live Bytes are only 1.01 MB the App crashes and why I still receive a memory warning (see black flags). Is it due to some pointer referencing to some null variable or due to an excessive memory allocation? 1.01 MB doesn't seem much to me..
EDIT 2: Following Marion's advice I used the Activity Monitor and realized that the effective real memory usage is 55.39 MB. I misinterpreted the "live bytes" word. I will try to dig into this further and will leave the question as unaccepted for now to allow other people contribute. If I won't have any other answer within one-two days I'll mark as accepted the current answer. Thanks!
Thanks a lot!
If you want to find leaks, use Leaks instrument instead of Allocations. To find out, how much memory use at the moment, use ActivityMonitor.
If you will have problems with memory in cocos2d, you can try to purge cache. In cocos2d you can purge CCTextureCache, CCSpriteFrameCache, CCAnimationCache. It will release unused textures and frames.
If you want to check if all of unnessesary textures were removed from memory, you can place breakpoint to CCTextureCache class and call, for example, sharedTextureCache and look throw the content of textures_ dictionary. Or add some method to this class to be able to dump current state of cache.

No memory leaks, yet still running out of memory?

In my cocos2d application I have run through it using instruments and removed all memory leaks. I have my game outputting how much memory is in use on the screen and it is constantly rising as the game progresses until I eventually run out of memory. The amount of objects on screen doesn't increase by very much each level. Its a fairly simple game so i should not be running out of memory so soon.
I am removing all objects from a level when it ends and reallocating new ones when a new level begins. Instruments tells me there are no memory leaks. When i run through instruments to show me where the allocations are the bulk of the problem doesn't seem to come from one place its all of my objects.
Any ideas what the issue might be?
Just because instruments doesn't show leaks, doesn't mean you're not still allocating memory you're not using. Pay attention to the ObjectAlloc graph and see if that is constantly rising without falling off.
If you allocate memory that you aren't using and can't clean up, that's just as bad as a leak, even though you haven't technically leaked anything because you've stashed some unused reference somewhere.
Look at how much memory you actually need to use or to keep for future use at any point in your app, then treat anything else previously allocated as a leak and fix it.
In Objective-C when using autorelease objects be wary of circular dependencies!
If you create object A and then an instance of object B and pass A to it, so that B retains A, and A also retains B (for example by adding it as child to A) you can easily setup a circular dependency and thus both objects won't be released.
Tip: add a -(void) dealloc method to all your scene classes, and set a breakpoint there. If you change a scene and its dealloc method isn't called after the scene transition has finished, you're leaking this scene (it's not released).
Try to find that leak by looking for a setup that's similar to the one I described above.
Be careful about autoreleased objects, since they are not released immediately. If you have sections with lots of allocations and autoreleasing, try using specific autorelease pools on them.
It happened to me when creating huge decision trees (using NSArrays) for a game AI.
A great way to check for objects that are aggregating in memory is to use Instruments' new (in Xcode 3.2.3) Heap Shot functionality.
Use the normal Allocations instrument against your running application. Perform a series of repetitive events that should come back to some known state (for example, go one level down in a navigation controller and come back). Every time you do this, click on the Mark Heap button in the left sidebar for the Allocations instrument (under the section heading Heapshot Analysis).
What this will do is mark the heap at each of the starting points for this repetitive action and compare the objects that have been created by that point with the objects that had been created by the time you marked the heap last. Only objects that have been created between those two points and are still alive in memory will be listed.
If you are accumulating objects, but they are either not leaks or are being missed by the Leaks tool, they should show up here. I've found a number of subtle memory buildups this way, particularly when you pair this with the UI Automation instrument to automate the repetitive actions you're testing.
The bulk of the problem seem to be that Sprites don't get released in cocos2d unless all actions have been stopped on those sprites. This is done using stopAllActions. Cheers for all the suggestions.

iPhone - application being ejected

I have an application that is being ejected by iPhone OS for "low memory".
I have passed it thru instruments and I see zero leaks, and memory usage is around 640 kb.
The application crashes when I add objects to the screen.
This is how it works. I have a UIImageView based class that is very simple and add a few properties to the objects. This class is used on the created objects.
When the user taps a button a new image of that class is created and added to self.view.
After about 15 objects added, the application is ejected with low memory warning.
Instruments report no significant memory usage. Even after 15 objects added, the ALL ALLOCATIONS entry never goes beyond 660 kb. Each object can be one out of five 120x120 pixels image.
If it is not object allocation or leaks, what can that be? Please tell me what directions should I follow to locate the problem.
Thanks for any help.
The ObjectAlloc instrument does not indicate all memory usage within your application. Views and other visual elements do not show their full size in ObjectAlloc, so you will want to use the Memory Monitor instrument to see the actual memory size of your application at any given time.
Also, just because Instruments does not report leaks does not mean they aren't there. Run your application through the Clang Static Analyzer to take another look for potential memory leaks (via Build | Build and Analyze under Xcode 3.2 or by downloading the standalone tool). Again, even if this passes and you still see continually increasing memory consumption you have a leak somewhere.
You mention using Quartz drawing in your comments. You need to remember that Core Foundation objects used in Quartz also follow a specific memory management model, where everything you create with a function having Create in its name must be released using a matching function like CFRelease(). This may not show up as a leak if you forget this, but it is.
Leaks are not your problem. Over-retention is.
Look at Object Allocations. If that graph just rises and rises, your app will be killed. What make the iPhone especially angry is when you are told to let go of some memory (low memory warning) and no memory is freed. Your code may just be an extreme case of this, but you should free up SOMETHING when you get this message.
I discovered the problem had nothing to do with my code. Every time I use quartz on the iPhone I have this kind of problem.
Quartz has a serious problem that has to be fixed. As far as I detected, it gets chunks of memory to perform drawing and does not release them even if you release all variables and references you use. Even if you put all variables nil.
Quartz is a memory eater and a source for crashes.
Here is a project I've created to demonstrate how Quartz can crash your project. Look for a method inside inside MyClass.m, called imageWithBorderFromImage. This method uses quartz to draw a dashed border around the object. Run the project and click several times in the button. Every time you click, a new object is added to the screen, on top of the previous one. After about 20 clicks the application is ejected by springboard. Before that you will see LOW MEMORY warning on console.
Before telling me that the problem is too many views created, disable the quartz method and see that the application does not crashes anymore. In fact I was able to click 80 times and was still able to continue clicking, but I stopped the app.
Download the project QuartzNightmare here

iPhone: Steadily increasing memory usage in apps using touches

I've observed similar behavior in an Apple example app and a game I am working on. In the game, the behavior is eventually causing the app to crash due to running out of memory. The example app is Touches.
At any point when touches are being tracked, which is when you're moving one of the objects around in Touches, and pretty much any time a touch is down in my game, memory usage goes up steadily, for as long as you continue moving the touch around. Once the touch sequence completes, the memory usage does not go back down. I've gotten Touches, which starts off using less than half a meg, up to about 4MB net allocations with a few minutes playing around. That memory is never deallocated.
So my question is: why does this memory never get deallocated? Am I fundamentally misunderstanding something? Is this a framework flaw? I've read some about issues with the accelerometer and touches leaking, but I'm not using the accelerometer at all in this game.
I apologize if this seems TOO elementary, but...
There's no chance you have NSZombiesEnabled set to YES, do you?
That would prevent the deallocation of any objects whatsoever, and if you did allocate new ones, then EVENTUALLY the app will run out of memory.
Use instruments to find what instances are not being deallocated. I had a similar problem, and all it came down to was that I was calling retain, but not release (due to a logic error).
Im in a very similar situation. In fact, if i just let me app run without touching anything (all it does is run an NSTimer to update the display). And i notice the memory slowly but steadily increasing in usage.
If there are memory leaks its not obvious. Because ive seen memory leaks popup whenever it detects one.
So does that mean there are undetectable memory leaks?