It occurred to me that this might be useful for someone just starting out in coding… if it is too basic (no pun intended) then this is not for you!
If anyone has a better way or sees an issue please post it!
BTW this will be using API 1 code as I know that off the top of my head … if interested, conversion to API 2 code is an exercise you can undertake if you want to.
I have come across situations where I want to collect a number of objects in a dictionary under a single key in a loop but don’t initially have an array of those objects and don’t know how many different keys I will have.
For someone just starting out, how to handle that may not be obvious as you can’t use the NEW operator to create an Array, as it not considered an object in Xojo.
Consider this code (I am leaving out some parts just to show the principle. I assume the TextStream has been created and is ready to be read and will be closed)
Dim theLine As String, TextStream as TextInput, theKey as String
Dim DataArray() as DataClass
Dim theDictionary as New Dictionary
While Not TextStream.EOF
theLine = TextStream.Readline
theKey = ParseKey(theLine)
If theDictionary.HasKey(theKey) Then
DataArray = theDictionary.value(theKey)
Else
Dim NewDataArray() as DataClass ' Serves the same purpose New does for objects
theDictionary.value(theKey) = NewDataArray
DataArray = NewDataArray
End if
DataArray.Append New DataClass(theLine)
Wend
So each key value has its own independent array of DataObjects.
BTW I could have written it this way:
Dim theLine As String, TextStream as TextInput, theKey as String
Dim theDictionary as New Dictionary
While Not TextStream.EOF
theLine = TextStream.Readline
theKey = ParseKey(theLine)
Dim DataArray() As DataClass ' Creates a New DataClass Array each time through the loop
If theDictionary.HasKey(theKey) Then
DataArray = theDictionary.value(theKey)
Else
theDictionary.value(theKey) = DataArray
End if
DataArray.Append New DataClass(theLine)
Wend
That gives the same result as the first code but uses one less variable and less code
The reason i do not do it that way is that it creates a new array each time through the loop, but if the key is already in the dictionary, I am just throwing it away, and I don’t like to waste!
-Karen