德尔福:TImage.Create导致访问冲突 [英] Delphi: TImage.Create causes Access violation

查看:183
本文介绍了德尔福:TImage.Create导致访问冲突的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我提前为新手问题道歉,但为什么会与下面的code访问冲突错误(创建(SelectorForm);行)?我试着用的主要形式作为所有者,但它并没有任何区别。

  VAR
  SelectorForm:TSelectorForm;
  ArrayOfImages:数组的TImage的[1..10]履行程序TSelectorForm.FormCreate(发件人:TObject的);
VAR
  循环:字节;
开始
  对于循环:= 1〜10做
  开始
    与ArrayOfImages [循环]做
    开始
      创建(SelectorForm);
    结束;
  结束;
结束;


解决方案

的问题是,你实际上这样做的:

  VAR
  imageVariable:TImage中;
开始
  imageVariable.Create(ParentForm);
结束;

由于创造正在呼吁其尚未赋值的变量方法,该方法是错误的。

您应该这样做:

  VAR
  imageVariable:TImage中;
开始
  imageVariable:= TImage.Create(ParentForm);
  尝试
    //使用对象
  最后
    FreeAndNil(imageVariable);
  结束;
结束;

或者更具体地说在code:

 的循环:= 1〜10做
开始
  ArrayOfImages [循环]:= TImage.Create(个体经营);
结束;

<击>不要忘记释放对象

编辑:接受@ andiw的评论和收回释放对象的一角。
EDIT2:接受@格里的评论,并使用自身作为所有者

I apologize in advance for a newbie question, but why do I get "Access violation" error with the code below (on the "Create(SelectorForm);" line)? I tried using the main form as the owner, but it didn't make any difference.

var
  SelectorForm: TSelectorForm;
  ArrayOfImages: Array [1..10] of TImage;

implementation

procedure TSelectorForm.FormCreate(Sender: TObject);
var
  Loop: Byte;
begin
  for Loop := 1 to 10 do
  begin
    with ArrayOfImages[Loop] do
    begin
      Create(SelectorForm);
    end;
  end;
end;

解决方案

The problem is that you are effectively doing this:

var
  imageVariable: TImage;
begin
  imageVariable.Create (ParentForm);
end;

Which is wrong because "Create" method is being called on the variable which hasn't been assigned yet.

You should do this:

var
  imageVariable: TImage;
begin
  imageVariable := TImage.Create (ParentForm);
  try
    //use the object
  finally
    FreeAndNil (imageVariable);
  end;
end;

Or more specifically in your code:

for Loop := 1 to 10 do
begin
  ArrayOfImages[Loop] := TImage.Create (Self);
end;

Don't forget to free the objects

EDIT: Accepting @andiw's comment and taking back the tip of freeing objects. EDIT2: Accepting @Gerry's comment and using Self as owner.

这篇关于德尔福:TImage.Create导致访问冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆