1

Lets say I have a number of objects:

@interface City : NSObject {
    NSString  *name;
    NSString  *country;
    int       yearFirstTimeVisited;
}

Which are stored in an Array of objects:

city = [[City alloc] initWithName:@"London":@"UK",2002];
[pickerValues addObject:city];
city = [[City alloc] initWithName:@"Paris":@"France",2003];
[pickerValues addObject:city];
city = [[City alloc] initWithName:@"LA":@"USA",2003];
[pickerValues addObject:city];

Now I want to load the cities in to a picker-wheel. Naturally I can do this manually:

pickerValues = [[NSMutableArray alloc] initWithObjects:@"London",@"Paris", @"LA",nil];

But this is results in 2 sets of data I have to maintain in the code. I'm sure that there is a better option. I have searched the web, but could not find anything.

Thanks

Vincent
  • 4,342
  • 1
  • 38
  • 37

2 Answers2

3

Even better, use Key-Value Coding. -[NSArray valueForKey:] will do the loop for you.

NSArray* pickerNames = [pickerValues valueForKey:@"name"];
Kurt Revis
  • 27,695
  • 5
  • 68
  • 74
2

You could make a new array for the picker.

NSMutableArray *pickerNames = [NSMutableArray arrayWithCapacity:[pickerValues count]];
for(City *city in pickerValues){
    [pickerNames addObject:[city name]];
}

It's also a best practice to prefix your custom classes like VCCity instead of just City. I picked VC from your username but it's common to pick letters from the project name.

keegan3d
  • 10,357
  • 9
  • 53
  • 77