iteration without for-each

Please share your functions/code-snips

iteration without for-each

Postby udo.killermann » Fri Jun 25, 2010 6:58 am

Hello Board,

this time I introduce NSEnumerator as a way to iterate over collections (here: Array). Have a look at the comments in the code and you should get an idea how it works. Please feel free to comment on this example.
Code: Select all
' brought to you by U. Killermann
' whilst there is no "for each" iterator in the current edition of Objective Basic
' we can come close to it using NSEnumerator as our friend
' NSEnumerator basically has two instance methods "allObjects" and "nextObject"
' most of the work is done by the classes we need to iterate it's instance over
' so for example NSArray (and NSMutableArray as well) has two instance methods that
' help us to iterate either from start to end or the other way arround, these are
' "objectEnumerator" and "reverseObjectEnumerator"
' as we cannot (at least I don't know how) extend existing classes (here Array)
' within Objective Basic I use its NS* equivalent (here NSMutableArray) to
' introduce the additional methods
' with this in place we can iterate over arrays without a need to know how many
' elements the array has
' I didn't measure any timing, but assume the use of NSEnumerator faster than
' for-next loop using myArray.Object(index) inside
' OB doesn't know anything about NSEnumerator thus we need to introduce it using
' the Declare mechanism
Declare Class "NSEnumerator"
Declare Function "NSEnumerator" - (NSArray *)allObjects
Declare Function "NSEnumerator" - (id)nextObject

' NSMutableArray is known by Objective Basic, but not the enumerator specific
' methods
Declare Function "NSMutableArray" - (NSEnumerator *)objectEnumerator
Declare Function "NSMutableArray" - (NSEnumerator *)reverseObjectEnumerator
Declare Function "NSMutableArray" - (void)addObject:(id)anObject

' BTW: You can use enumeration with NSDictionary and NSSet as well - perhaps I
' will cover this later (depending on demand)
Dim myArr As NSMutableArray
Dim myEnumerator As NSEnumerator
Dim theObject As id
Dim myArr2 As Array

Event AwakeFromNib()
  myArr2=Array("hund","katze","Maus", 7 , 42)
  myArr = myArr2
  ' enumerate from start to end
  myEnumerator = myArr.objectEnumerator()
  theObject = myEnumerator.nextObject() ' assingnemt
  Do While theObject <> Nil
    theObject = myEnumerator.nextObject()
  Alert("And now for something completely different!")
  ' enumerate from end to start
  myEnumerator = myArr.reverseObjectEnumerator()
  theObject = myEnumerator.nextObject() ' assignment
  Do While theObject <> Nil
      theObject = myEnumerator.nextObject()

End Event

Kind regards
MacBook (2GHz, 4 GByte) - Lion (10.7.3)
started Objective Basic coding in April 2010 - still enjoy it ;-)
Posts: 247
Joined: Thu Apr 08, 2010 6:46 am
Location: Hannover, Germany

Return to Code examples (Xcode 3)

Who is online

Users browsing this forum: No registered users and 1 guest