2

I'm trying to populate a UIPickerView with JSON data that is parsed into an NSArray.

The console shows that the JSON is parsing properly but the UIPickerView is remaining empty.

Here's my code:

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView 
{
    return 1;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    //set number of rows
    return self.terrainJsonArray.count;
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    //set item per row
    return [self.terrainJsonArray objectAtIndex:row];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Parse JSON 

    NSString *terrainString = [NSString stringWithFormat:@"http://terrainracing.com/ios/events_json.php"];

    NSURL *terrainUrl = [NSURL URLWithString:terrainString];

    NSData  *terrainData = [NSData  dataWithContentsOfURL:terrainUrl];

    NSError *error;

    NSArray *terrainJsonArray = [NSJSONSerialization JSONObjectWithData:terrainData options:kNilOptions error:&error];

    NSLog(@"%@", terrainJsonArray);
}

1 Answer 1

2

The picker view delegate methods are looking at the class instance variable self.terrainJsonArray (actually it's the property getter for the instance variable).

In viewDidLoad, you are declaring and logging a local variable named terrainJsonArray. This local variable has no connection to the instance variable.

You must be getting a compiler warning in viewDidLoad like "Local declaration of 'terrainJsonArray' hides instance variable".

Change this line:

NSArray *terrainJsonArray = [NSJSONSerialization JSONObjectWithData:terrainData options:kNilOptions error:&error];

to:

self.terrainJsonArray = [NSJSONSerialization JSONObjectWithData:terrainData options:kNilOptions error:&error];
Sign up to request clarification or add additional context in comments.

2 Comments

thanks so much! that fixed it. this is my first app not from a tutorial so i'm still learning the differences between instance/local etc.
also, sorry i cant vote the answer up, im new to the forum and not allowed yet.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.