Wish Classes: preserve value of private module variables after initialization

LucaMs

Expert
Licensed User
Longtime User
I tried something like:
B4X:
' MyClass - Class Module

Sub Class_Globals
    Private mInitialized As Boolean
End Sub

Public Sub Initialize(...)
    If mInitialized Then
    ' ...
    mInitialized = True
End Sub

but if I declare a variable of type MyClass and then I initialize it two times, mInitialized is always False.


I know I can use IsInitialized but I wish the class itself can deal with this eventuality.


Thank you
 

LucaMs

Expert
Licensed User
Longtime User
It is simple but... wrong too.

I would like to devise a method to create a Singleton class.

This question is wrong, though. I fear that I will have to invent something written on the device.

However, I am attaching a micro project.



Thanks, Erel.
 

Attachments

  • ClassInitialization.zip
    11.5 KB · Views: 184

HotShoe

Well-Known Member
Licensed User
Longtime User
Public Sub Initialize(...)
If mInitialized Then
' ...
mInitialized = True
End Sub

I think you mean to do somethi8ng like:

B4X:
Public Sub Initialize(...)

    If not(mInitialized) Then
    ' ... init code here
    mInitialized = True 
    End If

End Sub

--- Jem
 

LucaMs

Expert
Licensed User
Longtime User
My concept was wrong.

I meant:

B4X:
' MyClass - Class Module

Sub Class_Globals
    Private mInitialized As Boolean
End Sub

Public Sub Initialize(...)
    If mInitialized Then
        '  Prevent a second initialization
        Return
    End If
    ' ...
    mInitialized = True
End Sub

but this can be useful to prevent to "duplicate" the initialization of an object, it is not enough (it is wrong) to ensure the existence of one object only (Singleton class).
 
Last edited:

JordiCP

Expert
Licensed User
Longtime User
The logic would have to be backed by a process single variable
B4X:
Sub Process_Globals
  Dim mOnceInitialized as Bool = False
  '...
End Sub

And the class declaration...

B4X:
' MyClass - Class Module

Sub Class_Globals
  Private mInitialized As Boolean
End Sub

Public Sub Initialize(...)
  If not(mOnceInitialized) Then

    ' ...initialize other fields
    mInitialized=True
    mOnceInitialized=True
    Return
  EndIf
End Sub

Anyway,it is not possible to prevent the existence of more than one object, but this way will grant you that only the first one will be initialized
 
Top