This is my first time doing an iOS app, so I may not know some stuff that may seem easy. Please be patient with me =)
Basically, I need to fill up my UIPickerView with data from my JSON. I have successfully parsed my JSON data and pulled out what I need and placed them into an NSMutableArray. When I first tried to do the UIPickerView, I used hardcoded array, and everything was working fine. Now, when I try to replace the hardcoded array with my JSON array, I keep getting a null JSON array. The way it works, it seems that the UIPickerView tried to pull everything out before my JSON array is filled.
I have tried reloading the UIPickerView as suggested elsewhere on this site, and it also isn't working.
The following are parts of my code:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
dispatch_async(randomiserBgQ, ^{
NSData* data = [NSData dataWithContentsOfURL:randomiserCatURL];
[self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
- (void)fetchedData:(NSData *)responseData{
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSArray* randomiserCat = [json objectForKey:@"categories"];
self.randCatSel =[[NSMutableArray alloc] init];
NSLog(@"categories: %@", randomiserCat);
for (int i = 0; i < [randomiserCat count]; i++) {
NSDictionary *dict = [randomiserCat objectAtIndex:i];
NSString* parent = [dict objectForKey:@"name"];
[self.randCatSel addObject:parent];
NSArray* childrenArray = [dict objectForKey:@"children"];
for (int i = 0; i < [childrenArray count]; i++) {
NSDictionary* dict = [childrenArray objectAtIndex:i];
NSString* children = [dict objectForKey:@"name"];
[self.randCatSel addObject:children];
NSArray* grandchildrenArray = [dict objectForKey:@"grandchildren"];
for (int i = 0; i < [grandchildrenArray count]; i++) {
NSDictionary* dict = [grandchildrenArray objectAtIndex:i];
NSString* grandchildren = [dict objectForKey:@"name"];
[self.randCatSel addObject:grandchildren];
}
}
}
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent: (NSInteger)component
{
return [self.randCatSel count];
}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return [self.randCatSel objectAtIndex:row];
}
As you can see, the way I tried to parse my JSON data, I used such a long method as I have a few levels of arrays in the JSON data. If there is a faster method (like foreach in PHP), please point me in the right direction as well.
So far, my UIPickerView is getting a empty randCatSel array (I presume it is loading it before it is filled).
[pickerViewObj reloadAllComponents];after json parsing.