casting integer to TObject for TStringList Objects array lazarus / 31-LCL ---------------------------------------------------------------------- MarcusM · 2010-11-13 17:55 Hello, I am trying to store id (integer) values in the objects array of a TMemo's Lines property. However, when I access the values I always get '0' (zero) as the result. See my simple example below. How do I access the integer values? Code: [Select]procedure TForm1.Button1Click(Sender: TObject); begin {Memo1 is a TMemo that I added to the form} Memo1.Lines.Clear; Memo1.Lines.AddObject('hello', TObject(1)); Memo1.Lines.AddObject('in', TObject(2)); Memo1.Lines.AddObject('there', TObject(3)); end; procedure TForm1.Button2Click(Sender: TObject); var i: integer; begin for i := 0 to Memo1.Lines.Count - 1 do begin ShowMessage(IntToStr(integer(Memo1.Lines.Objects[i]))); end; end; here are reference sites that I have found. http://delphi.about.com/od/vclusing/a/items_addobject.htm http://www.experts- exchange.com/Programming/Languages/Pascal/Delphi/Q_26597662.html Thanks in advance. ---------------------------------------------------------------------- typo · 2010-11-13 18:16 This works fine: Code: [Select]var   sl :TStringList; procedure TForm1.Button3Click(Sender: TObject); begin   sl := TStringList.Create;   with sl do   begin     Clear;     AddObject('hello', TObject(1));     AddObject('in', TObject(2));     AddObject('there', TObject(3));   end; end; procedure TForm1.Button4Click(Sender: TObject); var i: integer; begin for i := 0 to sl.Count - 1 do begin ShowMessage(IntToStr(integer(sl.Objects[i]))); end;         sl.Free; end;      Why a TMemo? ---------------------------------------------------------------------- MarcusM · 2010-11-14 01:47 QuoteWhy a TMemo? I am writing an application for me to categorize my reading notes. When the user (me) selects a tag or does a search a TMemo is populated with the notes associated with that action. Each note represents a single line. What I want to happen is that when a line(s) is selected, the popup menu can be initiated allowing to edit note(s), delete note(s), or modify associated tags. For this reason I need to associate the note id with the note string. This should be my last hurdle to overcome before I can begin using the app. {I hope} I now see an error in the subject of this post. TMemo.Lines is a TStrings not TStringList. Looking at the documentation though, TStrings should support this functionality. Why does this not work with TMemo.Lines? http://lazarus-ccr.sourceforge.net/docs/rtl/classes/tstrings.html ---------------------------------------------------------------------- theo · 2010-11-14 07:54 Try TListBox instead of TMemo. ---------------------------------------------------------------------- typo · 2010-11-14 08:39 QuoteWhy does this not work with TMemo.Lines? TMemo is a Windows control and nothing that happens in it has a reasonable explanation. ---------------------------------------------------------------------- MarcusM · 2010-11-14 13:40 QuoteTMemo is a Windows control and nothing that happens in it has a reasonable explanation. LOL, but really this is a bummer. I do not want to use TListBox b/c I use TMemo in another spot for entering & editing the notes which has the same requirements for storing id's in the Objects array. There a text editor like interface is ideal. When viewing notes (as described above) it is desirable. I am now trying to install TRichView. ---------------------------------------------------------------------- theo · 2010-11-14 14:26 Quote from: MarcusM on November 14, 2010, 02:40:00 pmLOL, but really this is a bummer. I think what you want to do is a bit strange. A TMemo is not really "line based". What if the user enters a new line or deletes the line ending (merges two or more lines)? What happens to your objects then? Not to talk about word-wrapping etc. ---------------------------------------------------------------------- ringo · 2010-11-15 04:32 Quote from: theo on November 14, 2010, 03:26:57 pmQuote from: MarcusM on November 14, 2010, 02:40:00 pmLOL, but really this is a bummer. I think what you want to do is a bit strange. A TMemo is not really "line based". What if the user enters a new line or deletes the line ending (merges two or more lines)? What happens to your objects then? Not to talk about word-wrapping etc. None of that matters.  The Lines property in a TMemo has a TObject (a pointer) associated with each line.  If lines get merged or wrapped or whatever, it is up to the programmer to decide how to handle that.  The fact that a pointer is associated with each line means the programmer should be able to USE that pointer, even if it is only storing an integer value. To the OP: can you stor a *real* TObject there, and get it back intact? Ringo ---------------------------------------------------------------------- ivan17 · 2010-11-15 13:21 Quote from: MarcusM on November 14, 2010, 02:40:00 pmLOL, but really this is a bummer. really? was it that hard to throw in an array or a TObjectList (i'd prefer an array) and be done with it instead of insisting on a memo. by the way, i concur, don't use a memo. and seriously dude, if everyone tells you don't use a memo for that then don't use a memo for that. me, i'd make a multiline listbox and use a memo for editing single items inline. the simplest option i'd recomend for you would be KGrid with just one column (see the main demo). ---------------------------------------------------------------------- ringo · 2010-11-15 15:43 Two things: First, this conversion in a TMemo.Lines.Objects to and from an integer works fine for me.  I just wrote a small test program to store an integer in the Objects array, and convert it back to an integer; The relevant code is: procedure TForm1.FormCreate(Sender: TObject); var   i,n:  integer;   s:    string; begin   for i := 0 to 6 do     begin     s := IntToStr(i);     Memo1.Lines.Add(s);     Memo1.Lines.Objects := TObject(i);     end;   s := '';   for i := 0 to 6 do     begin     n := integer(Memo1.Lines.Objects);     s := s + IntToStr(n) + ', ';     end;   Memo1.Lines.Add(s); end;    Worked with no problems. Second item: why do some people insist on telling other people "don't do that"? Are they politicians or something?  Perhaps the "code police"? If somebody is using a particular construct, he/she usually has a good reason.  If they don't have a good reason, they'll ask for suggestions for a better component or construction.  Telling somebody "don't do that" is just a cheap way to say "I don't know what's wrong". Ringo ---------------------------------------------------------------------- ringo · 2010-11-15 15:48 Actually, the editor seemed to have "interpreted" my code sample; here it is again, hopefully without interpretation: procedure TForm1.FormCreate(Sender: TObject); var   i,n:  integer;   s:    string; begin   for i := 0 to 6 do     begin     s := IntToStr(i);     Memo1.Lines.Add(s);     Memo1.Lines.Objects[ i ] := TObject(i);     end;   s := '';   for i := 0 to 6 do     begin     n := integer(Memo1.Lines.Objects[ i ]);     s := s + IntToStr(n) + ', ';     end;   Memo1.Lines.Add(s); end;              Ringo ---------------------------------------------------------------------- MarcusM · 2010-11-17 12:46 Thanks Ringo. You're approach had me excited. Unfortunately, it only works when accessing the objects within the function they were added. The following does not work: Code: [Select]procedure TForm1.FormCreate(Sender: TObject); var   i: integer;   s: string; begin   for i := 0 to 6 do begin     s := IntToStr(i);     Memo1.Lines.Add(s);     Memo1.Lines.Objects[i] := TObject(i);   end; end; procedure TForm1.Button2Click(Sender: TObject); var   i, n: integer;   s: string; begin   s := '';   for i := 0 to 6 do begin     n := integer(Memo1.Lines.Objects[i]);     s := s + IntToStr(n) + ', ';   end;   Memo1.Lines.Add(s); end; ---------------------------------------------------------------------- MarcusM · 2010-11-17 13:09 Quotethe simplest option i'd recomend for you would be KGrid with just one column (see the main demo). Though I'm confident that if TMemo.Lines handled the Objects array as expected my app would work as I envisioned, KGrid looks like a potential alternative. However, I can't get Lazarus to install new components {I've got another thread going for that problem}. Quotecan you stor a *real* TObject there, and get it back intact? No, this doesn't work either. It prompts 'Access Violation', guessing that's because nothing is in the Object array. Code: [Select]procedure TForm1.btnAdd1Click(Sender: TObject); var   btn: TButton; begin   btn := TButton.Create(Form1);   Memo1.Lines.Clear;   Memo1.Lines.Add('hello');   Memo1.Lines.Objects[0] := TObject(btn); end; procedure TForm1.btnShow1Click(Sender: TObject); var   btn: TButton; begin  try     ShowMessage(Memo1.Lines.Objects[0].ClassName);   except on e: Exception do begin     ShowMessage(e.Message);     end;   end; end; ---------------------------------------------------------------------- ringo · 2010-11-17 16:04 I looked through the source code for TStrings and TStringList, and I found that TStrings actually does NOT implement the Objects array.  There are dummy functions there (with the virtual attribute) that are meant to be over-ridden by descendant classes. Class TStringList does implement the Objects array, so the example code above will work correctly. However, since TMemo uses TStrings instead of TStringList, the assignment to/from an integer will not work correctly. This does not seem to be a correct implementation of TStrings.  The original Delphi version of TStrings implements the Objects array (and is then inherited by TStringList). I am not sure, but does this qualify as a "bug" in TStrings? Ringo ---------------------------------------------------------------------- ivan17 · 2010-11-17 19:33 Quote from: ringo on November 17, 2010, 05:04:02 pmHowever, since TMemo uses TStrings instead of TStringList, the assignment to/from an integer will not work correctly. no, memo uses TMemoStrings, simpler descendant of TStrings.  TStrings itself is never directly used by anyone as it simply can not be used (it is an abstract class). it is used only as a placeholder for objects of descendant classes. Quote from: ringo on November 17, 2010, 05:04:02 pmHowever, since I am not sure, but does this qualify as a "bug" in TStrings? not in my book. Quote from: MarcusM on November 17, 2010, 02:09:53 pmThough I'm confident that if TMemo.Lines handled the Objects array as expected my app would work as I envisioned...did you envision a label above the memo (large red font) saying "please don't delete lines 2-5 in the input box below"? Quote from: MarcusM on November 17, 2010, 02:09:53 pmHowever, I can't get Lazarus to install new componentslet me check: open kgridlaz.lpk; click compile; nice; click install; wait; wait; wait; done; try - works (laz0.9.29, win32) i can send you the zip file (1,166,784 bytes) - pm me with mail. ---------------------------------------------------------------------- ringo · 2010-11-18 03:37 Quote from: ivan17 on November 17, 2010, 08:33:40 pmQuote from: ringo on November 17, 2010, 05:04:02 pmHowever, since TMemo uses TStrings instead of TStringList, the assignment to/from an integer will not work correctly. no, memo uses TMemoStrings, simpler descendant of TStrings.  TStrings itself is never directly used by anyone as it simply can not be used (it is an abstract class). it is used only as a placeholder for objects of descendant classes. No, the Lines is a TStrings; I don't know what a TMemoStrings is.  TMemo is derived from TCustomMemo, which defines Lines as a TStrings.  From the file "stdctrls.pp": { TCustomMemo }   TCustomMemo = class(TCustomEdit)   private     FHorzScrollBar: TMemoScrollBar;     FLines: TStrings;     FScrollBars: TScrollStyle;     FVertScrollBar: TMemoScrollBar;     FWantReturns: Boolean;     FWantTabs: boolean;     FWordWrap: Boolean;     procedure SetHorzScrollBar(const AValue: TMemoScrollBar);     procedure SetVertScrollBar(const AValue: TMemoScrollBar);   protected     class procedure WSRegisterClass; override;     procedure CreateParams(var Params: TCreateParams); override;     procedure InitializeWnd; override;     procedure FinalizeWnd; override;     function  RealGetText: TCaption; override;     procedure RealSetText(const Value: TCaption); override;     function GetCachedText(var CachedText: TCaption): boolean; override;     function GetCaretPos: TPoint; override;     procedure SetCaretPos(const Value: TPoint); override;     procedure SetLines(const Value: TStrings);     procedure SetSelText(const Val: string); override;     procedure SetWantReturns(const AValue: Boolean);     procedure SetWantTabs(const NewWantTabs: boolean);     procedure SetWordWrap(const Value: boolean);     procedure SetScrollBars(const Value: TScrollStyle);     procedure Loaded; override;     procedure ControlKeyDown(var Key: Word; Shift: TShiftState); override;     procedure CNChar(var Message: TLMKeyUp); message CN_CHAR;     class function GetControlClassDefaultSize: TSize; override;   public     constructor Create(AOwner: TComponent); override;     destructor Destroy; override;     procedure Append(const Value: String);   public     property Lines: TStrings read FLines write SetLines;     property HorzScrollBar: TMemoScrollBar read FHorzScrollBar write SetHorzScrollBar;     property VertScrollBar: TMemoScrollBar read FVertScrollBar write SetVertScrollBar;     property ScrollBars: TScrollStyle read FScrollBars write SetScrollBars default ssNone;     property WantReturns: Boolean read FWantReturns write SetWantReturns default true;     property WantTabs: Boolean read FWantTabs write SetWantTabs default false;     property WordWrap: Boolean read FWordWrap write SetWordWrap default true;   end; Here is the entire definition of TStrings, from file "classesh.inc".  I don't see anything that makes it an abstract class. { TStrings class }   TStrings = class(TPersistent)   private     FSpecialCharsInited : boolean;     FQuoteChar : Char;     FDelimiter : Char;     FNameValueSeparator : Char;     FUpdateCount: Integer;     FAdapter: IStringsAdapter;     FLBS : TTextLineBreakStyle;     FStrictDelimiter : Boolean;     function GetCommaText: string;     function GetName(Index: Integer): string;     function GetValue(const Name: string): string;     Function GetLBS : TTextLineBreakStyle;     Procedure SetLBS (AValue : TTextLineBreakStyle);     procedure ReadData(Reader: TReader);     procedure SetCommaText(const Value: string);     procedure SetStringsAdapter(const Value: IStringsAdapter);     procedure SetValue(const Name, Value: string);     procedure SetDelimiter(c:Char);     procedure SetQuoteChar(c:Char);     procedure SetNameValueSeparator(c:Char);     procedure WriteData(Writer: TWriter);   protected     procedure DefineProperties(Filer: TFiler); override;     procedure Error(const Msg: string; Data: Integer);     procedure Error(const Msg: pstring; Data: Integer);     function Get(Index: Integer): string; virtual; abstract;     function GetCapacity: Integer; virtual;     function GetCount: Integer; virtual; abstract;     function GetObject(Index: Integer): TObject; virtual;     function GetTextStr: string; virtual;     procedure Put(Index: Integer; const S: string); virtual;     procedure PutObject(Index: Integer; AObject: TObject); virtual;     procedure SetCapacity(NewCapacity: Integer); virtual;     procedure SetTextStr(const Value: string); virtual;     procedure SetUpdateState(Updating: Boolean); virtual;     property UpdateCount: Integer read FUpdateCount;     Function DoCompareText(const s1,s2 : string) : PtrInt; virtual;     Function GetDelimitedText: string;     Procedure SetDelimitedText(Const AValue: string);     Function GetValueFromIndex(Index: Integer): string;     Procedure SetValueFromIndex(Index: Integer; const Value: string);     Procedure CheckSpecialChars;   public     destructor Destroy; override;     function Add(const S: string): Integer; virtual;     function AddObject(const S: string; AObject: TObject): Integer; virtual;     procedure Append(const S: string);     procedure AddStrings(TheStrings: TStrings); virtual;     procedure Assign(Source: TPersistent); override;     procedure BeginUpdate;     procedure Clear; virtual; abstract;     procedure Delete(Index: Integer); virtual; abstract;     procedure EndUpdate;     function Equals(Obj: TObject): Boolean; override; overload;     function Equals(TheStrings: TStrings): Boolean; overload;     procedure Exchange(Index1, Index2: Integer); virtual;     function GetEnumerator: TStringsEnumerator;     function GetText: PChar; virtual;     function IndexOf(const S: string): Integer; virtual;     function IndexOfName(const Name: string): Integer; virtual;     function IndexOfObject(AObject: TObject): Integer; virtual;     procedure Insert(Index: Integer; const S: string); virtual; abstract;     procedure InsertObject(Index: Integer; const S: string;       AObject: TObject);     procedure LoadFromFile(const FileName: string); virtual;     procedure LoadFromStream(Stream: TStream); virtual;     procedure Move(CurIndex, NewIndex: Integer); virtual;     procedure SaveToFile(const FileName: string); virtual;     procedure SaveToStream(Stream: TStream); virtual;     procedure SetText(TheText: PChar); virtual;     procedure GetNameValue(Index : Integer; Out AName,AValue : String);     function  ExtractName(Const S:String):String;     Property TextLineBreakStyle : TTextLineBreakStyle Read GetLBS Write SetLBS;     property Delimiter: Char read FDelimiter write SetDelimiter;     property DelimitedText: string read GetDelimitedText write SetDelimitedText;     Property StrictDelimiter : Boolean Read FStrictDelimiter Write FStrictDelimiter;     property QuoteChar: Char read FQuoteChar write SetQuoteChar;     Property NameValueSeparator : Char Read FNameValueSeparator Write SetNameValueSeparator;     property ValueFromIndex[Index: Integer]: string read GetValueFromIndex write SetValueFromIndex;     property Capacity: Integer read GetCapacity write SetCapacity;     property CommaText: string read GetCommaText write SetCommaText;     property Count: Integer read GetCount;     property Names[Index: Integer]: string read GetName;     property Objects[Index: Integer]: TObject read GetObject write PutObject;     property Values[const Name: string]: string read GetValue write SetValue;     property Strings[Index: Integer]: string read Get write Put; default;     property Text: string read GetTextStr write SetTextStr;     property StringsAdapter: IStringsAdapter read FAdapter write SetStringsAdapter;   end; I think the lack of an Objects array in TStrings is a bug.  TStrings defines Objects with a type and with access methods, but not with storage (not even an abstract type).  This seems to me like somebody started to write the code for TStrings, then got side-tracked with some other issue, and never came back to finish the code. Ringo ---------------------------------------------------------------------- Zoran · 2010-11-18 08:54 Quote from: ringo on November 18, 2010, 04:37:22 amNo, the Lines is a TStrings; I don't know what a TMemoStrings is.  TMemo is derived from TCustomMemo, which defines Lines as a TStrings.  From the file "stdctrls.pp": The property is declared as TStrings, but in the constructor you can see how it is constructed: Code: [Select]constructor TCustomMemo.Create(AOwner: TComponent); begin   inherited Create(AOwner);   fCompStyle := csMemo;   FWantReturns := True;   FWantTabs := False;   FWordWrap := True;   FLines := TTextStrings.Create;   FVertScrollbar := TMemoScrollBar.Create(Self, sbVertical);   FHorzScrollbar := TMemoScrollBar.Create(Self, sbHorizontal);   AutoSelect := False;   AutoSize := False; end; So you see: Code: [Select]FLines := TTextStrings.Create;TTextStrings is the type. Quote from: ringo on November 18, 2010, 04:37:22 am Here is the entire definition of TStrings, from file "classesh.inc".  I don't see anything that makes it an abstract class. { TStrings class }   TStrings = class(TPersistent) ...     function Get(Index: Integer): string; virtual; abstract; ...     function GetCount: Integer; virtual; abstract; ...     procedure Clear; virtual; abstract;     procedure Delete(Index: Integer); virtual; abstract; ...     procedure Insert(Index: Integer; const S: string); virtual; abstract; ...   Now you do, don't you? This is from the bottom of this page:QuoteAn instance of TStrings is never created directly, instead a descendent class such as TStringList should be created. This is because TStrings is an abstract class which does not implement all methods; TStrings also doesn't store any strings, this is the functionality introduced in descendents such as TStringList. And this is from Delphi 7 help:QuoteDerive a class from TStrings to store and manipulate a list of strings. TStrings contains abstract methods and should not be directly instantiated. And from Emarcadero's site:QuoteDerive a class from TStrings to store and manipulate a list of strings. TStrings contains abstract or, in C++ terminology, pure virtual methods and should not be directly instantiated. ---------------------------------------------------------------------- ivan17 · 2010-11-18 09:01 let's leave the theory to rest. @ringo  don't quote half the lcl/rtl in somebody else's thread ---------------------------------------------------------------------- ringo · 2010-11-18 11:49 Quote from: ivan17 on November 18, 2010, 10:01:33 amlet's leave the theory to rest. @ringo  don't quote half the lcl/rtl in somebody else's thread Sorry, I got carried away. I still don't think it is working correctly, but this is probably a subject for a different thread. Ringo ---------------------------------------------------------------------- ringo · 2010-11-19 04:27 Just a clean-up note: This issue was found and reported to the bug-tracker back in 2007: 0009366: TStrings implementation in combo objects - TObject not working It's severity was changed from "major", then to "minor", then to "feature request". Ringo