您将如何解决以下内存泄漏问题?
我正在解决 iOS 应用程序 Ti SDK 6.2 中的内存泄漏问题,但收效甚微。
当打开和关闭窗口时,xcode Instruments Allocations 工具显示许多 TiUIxxxxProxy 对象保留在内存中。
为了测试/调试这个问题,我创建了一个 super 简单的经典 appcelerator 应用程序(代码如下所示)。使用下面的代码,我从 app.js 打开 window1,然后从 window1 上的按钮打开 window2。
您可以在随附的 xcode Instruments Allocations 图像中看到,在 window2 关闭后,代理对象仍然存在(窗口、表格等)。更糟糕的是,多次打开和关闭 window2 不断添加使用内存的额外代理对象。
App.js
require('Window1').CreateWindow().open();
Window1.js
exports.CreateWindow = function(){
try{
var window1 = Ti.UI.createWindow({
title:'Window 1',backgroundColor:'yellow',
});
var button1 = Ti.UI.createButton({
top:'50dp', center:'50%',
borderWidth:'1dp',borderColor:'black',
title:' Open Window 2 '
});
window1.add(button1);
button1.addEventListener('click', function() {
var win2 = require('Window2').CreateWindow();
win2.open();
});
return window1;
}
catch(e){
alert('Window 1 Error: ' + e);
}
};
Window2.js
exports.CreateWindow = function(){
try{
var window2 = Ti.UI.createWindow({
title:'Window 2',layout:'vertical'
,top:'200dp',bottom:'200dp',width:'80%'
,backgroundColor:'orange'
});
var button2 = Ti.UI.createButton({
top:'50dp', center:'50%',
borderWidth:'1dp',borderColor:'black',
title:' Close Window 2 '
});
window2.add(button2);
button2.addEventListener('click', function() {
window2.close();
});
// create a table row
var tvRow1 = Ti.UI.createTableViewRow({ });
//create a label to display location name
var labelRow1 = Ti.UI.createLabel({
color:'#000000',
left:'15dp',
top:'10dp',
text:'Label in row 1'
});
tvRow1.add(labelRow1);
// define table section for this group of rows
var tableViewSection1 = Ti.UI.createTableViewSection({ });
// push row into table view section
tableViewSection1.add(tvRow1);
//create array to store table sections
var arrayTableSections = [];
//add table section to array
arrayTableSections.push(tableViewSection1);
// create table
var table2 = Titanium.UI.createTableView({
data: arrayTableSections,
top:'50dp',
left:'50dp',
right:'50dp',
height:Ti.UI.SIZE,
backgroundColor:'#ffffff' ,
borderColor:'black',borderWidth:'1dp'
});
// add table to window
window2.add(table2);
return window2;
}
catch(e){
alert('Window 2 Error: ' + e);
}
};
最佳答案
您遇到的具体问题是您手动创建元素而不是清理。因此,在 Window2 结束时,您应该从其父元素中移除所有元素,并最终从 Window2 中移除,因此:
- 从行中删除标签
- 从该部分中删除该行
- 从表中删除该部分
- 从窗口中删除表格
- 从窗口中删除按钮
然后
- 取消标签、行、节、表和按钮
最重要的是:
- 清除指向节/行数组的指针。
完成后,确保你有一个 removeEvenlistener 关闭,以删除事件处理程序。
最后,关闭窗口并使其无效。
最后一件事,如果您以后不需要它,请不要在 window1 中创建 window2 指针,因此:
require("window2").createWindow().open();
优于:
var window2 = require("window2").createWindow();
window2.open();
这样做我能够打开 window2 8 次以上,然后一切都清理干净了。
关于ios - 您将如何解决以下内存泄漏问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46458068/