1

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

JonF
  • 2,336
  • 6
  • 38
  • 57

2 Answers2

3

You're looking for fast enumeration.

For your example, something like

for (PersonEntity *p in myNsArrayController.arrangedObjects)
{
    // Rest of your code
}
jrturton
  • 118,105
  • 32
  • 252
  • 268
1

You can also enumerate using blocks. For example:

[myNsArrayController enumerateObjectsUsingBlock:^(id object, NSUInteger index, BOOL *stop)
 {
       PersonEntity *p = object;
       // Rest of your code
 }];

There's pro's and cons to both approaches. These are discussed in depth in the answer to this question:

Objective-C enumerateUsingBlock vs fast enumeration?

You can find a great tutorial on blocks in Apple's WWDC 2010 videos. In that they say that at Apple they use blocks "all the time".

Community
  • 1
  • 1
Max MacLeod
  • 26,115
  • 13
  • 104
  • 132