Scott Scovell on Visual FoxPro

Thursday, November 03, 2005

Class name during Init()

While working on an enhancement to my label base class control Istumbled across a real gotcha with the way VFP instanicates objects

While working on an enhancement to my label base class control I stumbled across a real gotcha with the way VFP instantiates objects.

 

Craig had showed me some great code he had implemented on his label base class to allow user defined captions. On the Init() of the label control, a check would be made for a stored user defined caption in a table. If one is found, the caption property is set to the user defined value otherwise the default caption isused. The user was able to change the caption by right clicking on the control.I used the label object’s hierarchy, SYS(1272), as the key on my lookup table.

 

What I found was, during object instantiation the value returned by SYS(1272) differed to the returned value after the object was instantiated. This can be demonstrated with the following code example:

 

Local oLabel As Label

 

Clear

? "*** On Init ***"

_Screen.NewObject("NewInstance", "SubContainer")

 

? "*** After Init ***"

For Each oLabel In _Screen.NewInstance.Controls

      oLabel.Init()

Next

_Screen.NewInstance.Init()

 

* All done

_Screen.RemoveObject("NewInstance")

 

Return

 

Define Class SubContainer As BaseContainer

 

      * Try commenting out this line

      Name = "SubContainer"

 

      Add Object lblSubLabel As BaseLabel

 

EndDefine

 

Define Class BaseContainer As Container

 

      * Try commenting out this line

      Name = "BaseContainer"

 

      Function Init()

            ? "BaseContainer.Init: " + Sys(1272, This)

      EndFunc

 

      Add Object lblBaseLabel As BaseLabel

     

EndDefine

 

Define Class BaseLabel As Label

 

      Name = "BaseLabel"

 

      Function Init()

            ? "BaseLabel.Init: " + Sys(1272, This)

      EndFunc

     

EndDefine

 

After executing this code, you will notice the object name changes when the object's Init() method executes. Try commenting out the Name properties on each of the class definitions. Notice that the object name remains consistent during instantiation.

 

So the answer is simple, do not explicitly set object names when defining objects.Well, that’s fine in this example, but this is what VFP actually does within the VCX. Try browsing the VCX table and see for yourself what’s going on under the hood.

0 Comments:

Post a Comment

<< Home