How can I know if an object exists?

jesb4ppc

Member
Licensed User
Hi everyone,

I've got an error when I close a form and checks a method from an object. As it hasn't been created yet, I got an error (as expected). Not always the object is needed, so sometimes it doesn´t exists.

Is there a way to check if an object exists prior to use it? (similar to FileExist function).

Thanks in advance,

Jesus.
 

agraham

Expert
Licensed User
I assume that you mean an object from a library that has not yet had its' New method invoked. I can think of an arcane method that might work by assigning a B4PObject to the ControlRef of a HashTable from my Collections library but it is probably easier if you just New any existing objects in App_Start.
 

jesb4ppc

Member
Licensed User
Objet exists

Hi Erel and Agraham,

to Agraham: Yes, it was my first approach, but as the object not always exists, is not always needed to 'New' it.

to Erel: Tried your code, but I can´t parse the objet to Objetexist function.

I'll try to explain myself better. It's a Serial objet, and I got the 'undeclared array' error using Erel's code.

The error I got is in the following sentence:

Sub Form_Close
If Serial1.PortOpen=true Then Serial1.PortOpen = false
End Sub


If Serial1 hasn't been created with the New method, I can't use it (obviously). What I was looking for is something like this:

Sub Form_Close
If ObjetExist(Serial1.) Then
If Serial1.PortOpen=true Then Serial1.PortOpen = false
End if
End Sub


or

If Serial1.Exists then...

but this method doesn´t exists, isn´t it?

Thank you.
 

agraham

Expert
Licensed User
Erel's method does work but the result differs between the IDE and the optimised compiler for a pre-defined object. In the IDE the control exists even if it has not been Newed but when optimised it exists only after being Newed so this following code shows a "Yes" message box and Object appears in the list in the IDE, but optimised compiled there is no Yes message box and Object is absent from the control list.
B4X:
Sub Globals
   'Declare the global variables here.
   Dim Ctls (0) 
End Sub

Sub App_Start
   'Object.New1
   If ObjectExist("Object") Then
      Msgbox("Yes")
   End If
   Ctls() = GetControls("")
   For i = 0 To ArrayLen(Ctls())-1
      msg = msg & Ctls(i) & crlf
   Next
   Msgbox(msg)
End Sub

Sub ObjectExist(obj)
 ErrorLabel(ObjectExistErr)
  Dim a
  a = ControlType(obj)
  Return true
ObjectExistErr:
 Return false
End Sub
EDIT: Note that "Object.New1" is commented out.
 
Last edited:
Top