I am using the code below to parse an online XML file. When I run the application, my textfields are empty. How do I extract the strings from the NSXMLParser and put them into IBOutlets such as textfields, menu items, or labels?
interface file:
#import <Foundation/Foundation.h>
@interface XMLCurrent : NSObject <NSXMLParserDelegate> {
IBOutlet NSTextField *location;
IBOutlet NSTextField *condition;
IBOutlet NSTextField *degreesF;
NSMutableString *xmlLocation;
NSMutableString *xmlWeather;
NSMutableString *xmlTempF;
}
- (void)fetchCurrentWeather:(id)sender;
@end
implementation file:
#import "XMLCurrent.h"
@implementation XMLCurrent
- (void)fetchCurrentWeather:(id)sender {
NSURL *xmlURL = [NSURL URLWithString:@"http://www.weather.gov/xml/current_obs/KCLT.xml"];
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
[parser setDelegate:self];
[parser parse];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
if ([elementName isEqual:@"location"]) {
xmlLocation = [[NSMutableString alloc] init];
}
if ([elementName isEqual:@"weather"]) {
xmlWeather = [[NSMutableString alloc] init];
}
if ([elementName isEqual:@"temp_f"]) {
xmlTempF = [[NSMutableString alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
[xmlLocation appendString:string];
[xmlWeather appendString:string];
[xmlTempF appendString:string];
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if ([elementName isEqual:@"location"]) {
[location setStringValue:xmlLocation];
}
if ([elementName isEqual:@"weather"]) {
[condition setStringValue:xmlWeather];
}
if ([elementName isEqual:@"temp_f"]) {
[degreesF setStringValue:xmlTempF];
}
}
@end
I think there could be two reasons of your problem:
You're parsing XML before the viewDidLoad
was called, and that's why all your outlets are nil
You didn't connect them in Interface Builder.