gpt4 book ai didi

IOS + 德尔福 : low memory warnings - possible memory leak with TTexture?

转载 作者:行者123 更新时间:2023-11-29 11:50:58 25 4
gpt4 key购买 nike

在 iOS 下,当我频繁使用我的应用程序时,我总是会在几次后收到内存不足警告,然后我的应用程序会崩溃。所以我做了这个简单的测试:

var MyTexture : Texture;

while true do begin
MyTexture := buildTexture(aStream);
MyTexture.free;
MyTexture := nil;
end;

通常这必须毫无问题地运行。但是,一两分钟后,我收到了低内存警告,并且在我的应用关闭后不久。

为什么我这里有内存泄漏?

更新/注意

我整天都在努力找出问题所在,并给出一个完整的工作示例。问题不在于纹理,而在于 UIIMAGE 的使用。所以我在下面重现了一个工作示例(你只需要将你想要的任何 jpg 资源添加到项目中并将其命名为“测试”)

uses iOSapi.UIKit,
iOSapi.Foundation;

Procedure CreateAndFreeUIImage(const aStream: TCustomMemoryStream);
var aImage: UIimage;
aData: NSData;
begin
aData :=
TNSData.Wrap(TNSData.alloc.initWithBytesNoCopy(
aStream.Memory, // bytes: A buffer containing data for the new object.
// If flag is YES, bytes must point to a memory block
// allocated with malloc.
aStream.Size, // length: The number of bytes to hold from bytes.
// This value must not exceed the length of bytes.
False)); // flag: If YES, the returned object takes ownership of the
// bytes pointer and frees it on deallocation.
try
if aData.length > 0 then begin
aImage :=
TUIImage.Wrap(TUIImage.alloc.initWithData(aData));
// Return Value: An initialized UIImage object,
// or nil if the method could not initialize the image from the specified data.
if aImage <> nil then begin
try
// this to force the creation of the image
TpointF.Create(aImage.size.Width, aImage.size.Height);
finally
aImage.release;
aImage := nil;
end;
end
end;
finally
aData.release;
aData := nil;
end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var aStream: TResourceStream;
begin

aStream := TResourceStream.Create(HInstance, 'test', RT_RCDATA);
button1.Tag := button1.Tag + 1;
button1.Text := 'running ('+inttostr(button1.Tag) + ' thread(s))';

TThread.CreateAnonymousThread(
procedure
begin
while true do begin
CreateAndFreeUIImage(aStream);
// sleep(100); // << if you uncomment this then it's work !
end;
end).Start;

end;

因此,当您单击按钮时,您将创建并释放(在无限循环中)一个 UIImage。很快您就会在日志中收到一个低内存警告,然后是应用程序的硬关闭。

只需在循环中添加 sleep(100) 然后应用程序将永远不会崩溃(至少我没有看到它崩溃)

还要删除一个假设,来自 https://developer.apple.com/reference/uikit/uiimage可以看到uiimage是多线程的(所以错误不在这上面)

所以在我们释放对象后内存并没有立即清除,这导致内存随着我们创建的对象多于内存释放而增长(这是我的理解)。 p>

这是一个错误吗?解决方法是什么?他们有什么办法强制释放图像(或释放内存垃圾?)

最佳答案

好的,我找到问题了!在 iOS 中,对象不会立即释放,而是在下一次自动释放迭代后释放(对我来说这听起来很疯狂)。

所以解决方法非常简单:

AutoReleasePool := TNSAutoreleasePool.Create;
try
... do you code
finally
AutoReleasePool.release; // << will free right now all the object
end;

现在我不知道使用这个的速度损失......

关于IOS + 德尔福 : low memory warnings - possible memory leak with TTexture?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41221520/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com