listdelphirecordtframe

delphi: how to to store TCustomFrames and records in one list


I am using a TObjectList<TCustomFrame> to store TCustomFrames. Now i want to store some more information regarding to the TCustomFrame in the same list. A record would be nice.

Which delphi class would you prefer to store TCustomFrames and records in the same list?

The TCustomFrames and records will be added at runtime.


Solution

  • Create a single record to hold all the information:

    type 
      TFrameInfo = record
        Frame: TCustomFrame;
        Foo: string;
        Bar: Integer;
      end;
    

    Hold that in a TList<TFrameInfo>.

    I note that you were using TObjectList<T> rather than TList<T>. The only good reason for doing that would be if you were setting OwnsObjects to True. But that seems unlikely since I doubt that the list is really in charge of the lifetime of your GUI objects. As a note for the future, if you find yourself using TObjectList<T> with OwnsObjects set to False then you may as well switch to TList<T>.

    Now, in case you do need the list to control the lifetime then you'd be best using a class rather than a record for TFrameInfo.

    type 
      TFrameInfo = class
      private
        FFrame: TCustomFrame;
        FFoo: string;
        FBar: Integer;
      public
        constructor Create(AFrame: TCustomFrame; AFoo: string; ABar: Integer);
        destructor Destroy; override;
        property Frame: TCustomFrame read FFrame;
        // etc.
      end;
    
      constructor TFrameInfo.Create(AFrame: TCustomFrame; AFoo: string; ABar: Integer);
      begin
        inherited Create;
        FFrame := AFrame;
        // etc.
      end;
    
      destructor TFrameInfo.Destroy; 
      begin
        FFrame.Free;
        inherited;
      end;
    

    And then hold this in a TObjectList<TFrameInfo> with OwnsObjects set to True.