Simple memory question

You must Login before you can answer or comment on any questions.

I have a problem with memory leaks in Titanium. The reason for this is of course because I don't remove all references to the same object so it doesn't get deleted by the garbage collector.

However, when I started explicitly setting variables to null I noticed one thing. This is the most basic version of my code:

for (var i = 0; i < n; i++){
 
    // ... a new variable button is generated...    
 
    view.add(button);
    button = null;
}
Now, I expect that when I add the button to the view, it gets a reference to the button and not a copy. After that I set my variable button to null so it gets garbage collected in the next iteration of the for loop.

But, if this button was passed by reference to the view, then it should be destroyed in the view too, but it isn't. It is properly displayed on the screen.

What is wrong with my way of thinking here? How should I protect myself from memory leaks caused by generating new objects inside a loop? Any word of advice would be greatly appreciated.

— asked 9 months ago by Dino Trnka
1 Comment
  • Also, variable view was defined and initialized outside of the loop.

    — commented 9 months ago by Dino Trnka

3 Answers

You should remove the button from the view with view.remove(button), then when nulling it out, it will be garbage collected. If your buttons and views have references stored in local variables then those will be garbage collected when the function falls out of scope.

you can refer https://wiki.appcelerator.org/display/guides/Managing+Memory+and+Finding+Leaks

First remove button from view then make it null.

Your Answer

Think you can help? Login to answer this question!