Search code examples
xcodearraysuipickerview

Use initWithObjects on data from Array of Objects


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


Solution

  • 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.