10.3. Lists: Managing Objects in the Model Swarm

In the swarmapps package, one can find the Hello World example exercises. This exercise provides a good example of the way in which lists are used to organize the agents in a model swarm. In section three of the Hello World package, a list of people called pplList is created. Here is a skeleton showing the important commands that create and use the List protocol in the model swarm level. The file is called PplModelSwarm.m.

@implementation PplModelSwarm

- buildObjects
{ 
  //...
  // build the list to keep track of the ppl
  pplList = [List create: [self getZone]];
  for (inci = 0; inci < numPpl; inci++)
   {
    Person * person;
    id name;
    // allocate memory for a temporary person
    person = [Person createBegin: [self getZone]];
    //... 
    [person setWorld: pplList Room: room Party: self];
    //...
    person = [person createEnd];

    // add the person to the list of people
    [pplList addLast: person];
  }
}
- buildActions
{
  //...
  modelActions createActionForEach: pplList message: M(step)];
  //...
}
      

As in most Swarm examples, the list is created in the buildObjects method. The List class object is a "factory object," it can create instances that can answer to the List protocol. In this case, the list is called pplList.

In order to instruct the factory object List to manufacture an object that acts like a List, one would ordinarily have to import the collections.h header file. However, as in many Swarm examples, the collections.h file has already been included in a file that has been included in this file, and so an explicit import statement is not needed.

After an object that responds to the List protocol is created, then objects can be added onto that list. In this example, after pplList is created, then the buildObjects method proceeds into a for loop that creates the people objects. At the end of that loop, each person is added to the pplList by the command:

[pplList addLast: person];
      

The Swarm libraries take care of allocating memory and all the other details.

Once this list of people is created, what happens? In this case, the list of people becomes the central organizing element of actions that are to be scheduled. The object modelActions is told to go through the people list, one at a time, and cause each person to carry out its step method. The ins-and-outs of activity and schedule design are discussed elsewhere. This createActionForEach method works because the target is a Swarm collection item, the pplList, and the Swarm library knows how to traverse through the list of people.