CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Feb 1999
    Posts
    6

    Implementing an array of objects



    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

  2. #2
    Join Date
    Nov 1998
    Posts
    1

    Re: Implementing an array of objects



    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

  3. #3
    Join Date
    Apr 1999
    Posts
    16

    Re: Implementing an array of objects



    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



Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured