11.10 Enumeration in Objective-C classes

Fast enumeration in Objective-C is a construct which allows to enumerate the elements in a Cocoa container class in a generic way. It is implemented using a for-in loop in Objective-C.

This has been translated to Objective-Pascal using the existing for-in loop mechanism. Therefor, the feature behaves identically in both languages. Note that it requires the Objective-C 2.0 mode switch to be activated.

The following is an example of the use of for-in:

{$mode delphi}  
{$modeswitch objectivec2}  
 
uses  
  CocoaAll;  
 
var  
  arr: NSMutableArray;  
  element: NSString;  
  pool: NSAutoreleasePool;  
  i: longint;  
begin  
  pool:=NSAutoreleasePool.alloc.init;  
  arr:=NSMutableArray.arrayWithObjects(  
    NSSTR(’One’),  
    NSSTR(’Two’),  
    NSSTR(’Three’),  
    NSSTR(’Four’),  
    NSSTR(’Five’),  
    NSSTR(’Six’),  
    NSSTR(’Seven’),  
    nil);  
 
  i:=0;  
  for element in arr do  
    begin  
      inc(i);  
      if i=2 then  
        continue;  
      if i=5 then  
        break;  
      if i in [2,5..10] then  
        halt(1);  
      NSLog(NSSTR(’element: %@’),element);  
    end;  
  pool.release;  
end.