Recent

Author Topic: Unit StringList create and destroy [SOLVED]  (Read 752 times)

Pe3s

  • Hero Member
  • *****
  • Posts: 590
Unit StringList create and destroy [SOLVED]
« on: November 27, 2024, 10:58:56 pm »
Hello forum members, how can I create an object in a separate unit module so as not to create and delete it in Form Create and Destroy.
I want it to be created and destroyed in the unit module.
Code: Pascal  [Select][+][-]
  1. FImages := TStringList.Create;
« Last Edit: November 28, 2024, 09:03:57 am by Pe3s »

ackarwow

  • Full Member
  • ***
  • Posts: 128
    • Andrzej Karwowski's Homepage
Re: Unit StringList create and destroy
« Reply #1 on: November 27, 2024, 11:03:53 pm »
Hi @Pe3s

For example in this way:

Code: Pascal  [Select][+][-]
  1. unit TestUnit;
  2.  
  3. {$mode ObjFPC}{$H+}
  4.  
  5. interface
  6.  
  7. uses
  8.   Classes, SysUtils;
  9.  
  10. var
  11.   FImages: TStrings;
  12.  
  13. implementation
  14.  
  15. initialization
  16.  
  17. FImages:=TStringList.Create;
  18.  
  19. finalization
  20.  
  21. if Assigned(FImages) then
  22.   FreeAndNil(FImages);
  23.  
  24. end.
  25.  

Pe3s

  • Hero Member
  • *****
  • Posts: 590
Re: Unit StringList create and destroy
« Reply #2 on: November 27, 2024, 11:07:08 pm »
@ackarwow
Hello, I wonder if using constructor and destructor will also be good ?

cdbc

  • Hero Member
  • *****
  • Posts: 1786
    • http://www.cdbc.dk
Re: Unit StringList create and destroy
« Reply #3 on: November 27, 2024, 11:07:21 pm »
Hi
Another example:
Code: Pascal  [Select][+][-]
  1. unit Unit1;
  2.  
  3. {$mode ObjFPC}{$H+}
  4.  
  5. interface
  6.  
  7. uses
  8.   Classes, SysUtils;
  9.  
  10. function GetImageList: TStringList;
  11.  
  12. implementation
  13. var
  14.   FImages: TStringList = nil;
  15.  
  16. function GetImageList: TStringList;
  17. begin
  18.   if not Assigned(FImages) then FImages:= TStringList.Create;;
  19.   Result:= FImages;
  20. end;
  21.  
  22. finalization
  23.   FImages.Free;
  24.  
  25. end.  
Regards Benny
If it ain't broke, don't fix it ;)
PCLinuxOS(rolling release) 64bit -> KDE5 -> FPC 3.2.2 -> Lazarus 2.2.6 up until Jan 2024 from then on it's: KDE5/QT5 -> FPC 3.3.1 -> Lazarus 3.0

ackarwow

  • Full Member
  • ***
  • Posts: 128
    • Andrzej Karwowski's Homepage
Re: Unit StringList create and destroy
« Reply #4 on: November 27, 2024, 11:14:23 pm »
@ackarwow
Hello, I wonder if using constructor and destructor will also be good ?
Yes, you can use constuctor and destructor directly, although in case of destructor I prefer use it indirectly (via MyStrings.Free or FreeAndNil(MyStrings)).

Pe3s

  • Hero Member
  • *****
  • Posts: 590
Re: Unit StringList create and destroy
« Reply #5 on: November 28, 2024, 09:03:45 am »
Thank you  :)

 

TinyPortal © 2005-2018