Click to See Complete Forum and Search --> : Implementing an array of objects


Rick Okrasinski
November 20th, 1998, 09:33 AM
How do I implement an array of MyObject. What I am trying to do is create an array of objects so that I can go back and forth between objects in memory and make sure that I destroy all the objects on exit. Is it even possible???


Rick

Stephen Howell
November 21st, 1998, 09:06 AM
You can use the 'Collection' feature in VB, either create a collection of your objects or use the collection objects themselves - collections allow you to store various differing types of objects/data in an intelligent array with built in functions. VB5 - Class Builder Utility (Add-Ins Menu) has a collection builder too. Hope this helps.


Stephen

James Grant
November 27th, 1998, 10:46 AM
Rick-


Using arrays:



Private myObjArray() As MyObject

Private objCount As Long


Private Sub Form_Load()

objCount = 0

End Sub


'' Add a new object

Private Sub Command1_Click()

objCount = objCount + 1


'' Increase the array size

Redim Preserve myObjArray(1 To objCount) as MyObject


Set myObjArray(objCount) = New MyObject

End Sub


'' Destroy all objects

Private Sub Form_Unload(Cancel As Integer)

Dim i As Long


If (objCount > 0) Then

For i = 1 To objCount

Set myObjArray(i) = Nothing

Next i

End If

End Sub




Stephen is correct that Collections might be a better solution:



Private myObjects As Collection


'' Add a new object

Private Sub Command1_Click()

Dim obj As MyObject


Set obj = New MyObject


Call myObjects.Add(obj)


'' Remove local reference, only reference will now be from the Collection

Set obj = Nothing

End Sub


'' Destroy all objects

Private Sub Form_Unload(Cancel As Integer)

'' Theoretically Collections should clean up the data

'' but I like doing it myself to be safe.


Do While (myObjects.Count > 0)

Call myObjects.Remove(1)

Loop

End Sub




Hope it helps...


By the way, make sure you test this... it was off the top of my head. A great way is to put a Debug.Print "I'm dead" in your Class_Terminate to make sure they all go away.


-Jim