Search code examples
macoscocoacore-datanstableviewnsarraycontroller

Iterate over NSTableview or NSArrayController to get data


I have an NSTableview which s bound to a NSArrayController. The Table/Arraycontroller contains Core Data "Person" entities. The people are added to the NSTableview by the GUI's user.

Let's say a person entity looks like

NSString* Name;
int Age;
NSString* HairColor;

Now I want to iterate over what is stored in the array controller to perform some operation in it. The actual operation I want to do isn't important I don't really want to get bogged down in what I am trying to do with the information. It's just iterating over everything held in the NSArraycontroller which is confusing me. I come from a C++ and C# background and am new to Cocoa. Let's say I want to build a NSMutableArray that contains each person from nsarraycontroller 1 year in the future.

So I would want to do something like

NSMutableArray* mutArray = [[NSMutableArray alloc] init];

foreach(PersonEntity p in myNsArrayController)  // foreach doesn't exist in obj-c
{

  Person* new_person = [[Person alloc] init];
  [new_person setName:p.name];
  [new_person setHairColor:p.HairColor];
  [new_person setAge:(p.age + 1)];
  [mutArray addObject:new_person];

}

I believe the only thing holding me back from doing something like the code above is that foreach does not exist in Obj-c. I just don't see how to iterate over the nsarraycontroller.

Note: This is for OSX so I have garbage collection turned on


Solution

  • You're looking for fast enumeration.

    For your example, something like

    for (PersonEntity *p in myNsArrayController.arrangedObjects)
    {
        // Rest of your code
    }