我正在使用下面的代碼來解析在線XML文件。當我運行該應用程序時,我的文本字段爲空。如何從NSXMLParser中提取字符串並將它們放入IBOutlets(如文本字段,菜單項或標籤)?無法將NSXMLParser數據轉換爲文本字段,菜單項或標籤
接口文件:
#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
實現文件:
#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
您的代碼看起來不錯,您確定您的IBOutlet已正確連接? – dasblinkenlight 2012-02-15 16:03:06
你試過在調試器中停下來看看插座不是零嗎? – dasblinkenlight 2012-02-15 16:34:51
構建您的程序以在模擬器中運行,通過單擊編輯器文本空間左側的垂直條上的if([elementName isEqual:@「location」])''行上設置斷點並運行啓用了斷點。一旦你的斷點被擊中,將光標懸停在「位置」變量上以查看其值。 – dasblinkenlight 2012-02-15 16:49:48