I have been trying to fill an array in Xcode with xml output from a php script so that ios can connect to mysql. However, I keep getting an empty value for my array despite the fact that there is information in mysql. That must mean that either my attribute section or my parsing of the xml is wrong, but I really don't know what it is that actually is wrong (and no amount of starring at it seems to help). I am not getting any errors from php or xcode. Any ideas?
EDIT: I have followed the suggestions below and I am still getting an empty value, although I believe that it is coming from my php...
- (void)viewDidLoad
{
[super viewDidLoad];
char *cStr = "YES";
NSString *str3 = [NSString stringWithUTF8String:cStr];
NSString *urlString = [NSString stringWithFormat:@"(censored)", _login];
NSXMLParser *Parser = [[[NSXMLParser alloc] initWithContentsOfURL:[NSURL URLWithString:urlString]] autorelease];
[Parser setDelegate:self];
[Parser parse];
NSDictionary *itemAtIndex =(NSDictionary *)[oneam objectAtIndex:0];
oneam = [[NSMutableArray alloc] init];
if (([[itemAtIndex objectForKey:@"its"]isEqualToString:str3 ])) {
[switch1 setOn:YES animated:YES];
}
else {
[switch1 setOn:NO animated:YES];
}
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
if ( [elementName isEqualToString:@"location"]) {
[oneam addObject:[[NSDictionary alloc] initWithDictionary:attributeDict]];
NSLog(@"The array is %@", oneam);
}
}
And here is my php...
<?php
$login = "hello";
$dbh = new PDO('(censored)');
$sql = "SELECT oneam FROM login WHERE username = '$login'";
$q = $dbh->prepare( $sql );
$doc = new DOMDocument();
$r = $doc->createElement( "oneam" );
$doc->appendChild( $r );
foreach ( $q->fetchAll() as $row) {
$e = $doc->createElement( "location" );
$e->setAttribute( 'its', $row['oneam']);
$r->appendChild( $e );
}
print $doc->saveXML();
?>
I don't know if you maybe have them somewhere else, but you're missing 2 methods I've always used when doing .xml parsing: foundCharacters and didEndElement. I followed this tutorial set (all 3 videos - about 40 min worth), and after using it on a couple different instances it really helped me understand how to use the NSXMLParsers. Maybe try following his methods and see if that clears things up for you.
So where should I place "oneam = [[NSMutableArray alloc] init];". Everywhere I've placed it seems to declare it empty or null...
Whenever I use any type of array I always use lazy initialisation, so if it's null it's initialised in the getter method, like so:
-(NSMutableArray *)oneam
{
if (!_oneam){
_oneam = [[NSMutableArray alloc] init];
}
return _oneam;
}
When I @synthesize, I make sure it's defined like:
@synthesize oneam = _oneam;