I got a method to loop through an XML document. The method has a Do-While Loop like this:
do {
if([[TBXML elementName:element] isEqualToString:@"establishment"]) {
NSString *establishment= [TBXML textForElement:element];
NSLog(establishment);
[establishment release];
}
if (element->firstChild)
[self traverseElement:element->firstChild];
// Obtain next sibling element
} while ((element = element->nextSibling));
What i want to do is: Each time the loop passes the node it has to write
[TBXML textForElement:element];
To an UIPickerView. The number of establishments is dynamic, so i never know in advance.
EDIT:
Is this the right way to fill my array?
- (void) traverseElement:(TBXMLElement *)element {
do {
if([[TBXML elementName:element] isEqualToString:@"establishment"]) {
NSString *establishmentName = [TBXML textForElement:element];
NSMutableArray *stringsArray;
[stringsArray addObject:establishmentName];
}
// if the element has child elements, process them
if (element->firstChild)
[self traverseElement:element->firstChild];
// Obtain next sibling element
} while ((element = element->nextSibling));
}
Because i don’t have a clue where i have to alloc the uipickerview. Should i do that in my method where i am parsing the XML?
And i don’t know where to get the datasource..
I think you’ll probably want to setup a NSMutableArray that holds all the strings that you want to appear in the UIPickerView.
To respond to your edit, I would likely create the array in the header file (assuming this is all happening in a UIViewController). Define it as:
Then in your ViewDidLoad (or init, or loadView) method you’ll want to initialize it. In your code, you are doing so every time it finds an element, so it’s not being persisted and you’ll be creating a whole bunch of 1 element arrays.
Then of course you’ll want to release it in your dealloc method (and possibly your ViewDidUnload if you did it in ViewDidLoad).
Then when you create the UIPickerView, you’ll want to set its data source and delegate to your view controller. In those methods, they will pull from the array that your XML parsing adds elements to, and display them accordingly. Here’s some code to make sense of this:
Your header file will look something like this too:
You are basically instructing this view controller to supply all the data to your picker view. When the picker view is created, it looks to the following methods to fill in the appropriate data and display the picker view graphically.
Then here are the datasource methods:
I think after your parser finds things, if it’s adding them while the picker view is on screen, you’ll want to call reload on it: