Delphi: TImage.Create causes an access violation

I apologize in advance for the beginners question, but why am I getting the "Access Violation" error using the code below (in the line "Create (SelectorForm);")? I tried to use the main form as the owner, but that 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; 
+4
source share
2 answers

The problem is that you are effectively doing this:

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

This is incorrect because the Create method is called in a variable that has not yet been assigned.

You must 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; 

Do not forget to free objects

EDIT: Accept @andiw comment and return the end of the release of objects. EDIT2: Accepting @Gerry's comment and using Self as owner.

+17
source

There are many problems with the above code. (do not use "C" as it is for starters, do not use bytes for your var loop)

My guess is that you end up wanting to get an array of TImage instances created with the form as the parent.

so based on this assumption ... you want something like (untested)

 var ArrayOfImages: Array [0..9] of TImage; i : integer; begin for i := 0 to 9 do begin ArrayOfImages[i] := TImage.Create(theForm); end; end; 

Now pay attention: you will be responsible for cleaning the array, when you finish using it, you will need to call each instance of the image for free.

0
source

Source: https://habr.com/ru/post/1286660/


All Articles