How to save and load an array of a selfdefined type


SaveArrayOfMyObject.png
' Gambas class file

PRIVATE arCars AS Object[]
PRIVATE cnt AS Integer

PUBLIC SUB _new()
    'make an array with cnt cars in it
    i AS Integer
    DIM tmpcar AS CCar
    cnt = 5
    arCars = NEW Object[]
    FOR i = 0 TO cnt
        tmpcar = NEW CCar(Str(i), i + 14)
        arCars.add(tmpcar)
    NEXT
END

PUBLIC SUB Button1_Click()
    'save it to a file
    myFile AS File
    i AS Integer
    IF Dialog.SaveFile() THEN RETURN
        TRY OPEN Dialog.Path FOR CREATE AS myFile
             FOR i = 0 TO cnt
                 arCars[i].writeTo(myFile)
             NEXT
        CLOSE myFile
END

PUBLIC SUB Button2_Click()
    'load the file and write the brands and the PS_Power
    'into the TextLabel
    i AS Integer
    wort AS String
    myFile AS File
    tmpcar AS CCar
    newCars AS Object[]
    newCars = NEW Object[]
    i = 0
    IF Dialog.OpenFile() THEN RETURN
        TRY OPEN dialog.Path FOR READ AS myFile
            IF ERROR THEN message.Info("Can't open File")
            DO WHILE NOT Eof(myFile)
                tmpcar = NEW CCar
                newCars.add(tmpcar)
                newCars[i].ReadFrom(myFile)
                i = i + 1
            LOOP
        CLOSE myFile
    FOR i = 0 TO newCars.length-1
        wort = wort & Str(newCars[i].getBrand()) &
             ", " & Str(newCars[i].getPS_Power()) &
             " <br> "
    NEXT
    TextLabel1.Text = wort
END

-- JochenGeorges - 07 Jan 2005