2012-02-15 72 views
1

我正在使用下面的代碼來解析在線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 
+0

您的代碼看起來不錯,您確定您的IBOutlet已正確連接? – dasblinkenlight 2012-02-15 16:03:06

+0

你試過在調試器中停下來看看插座不是零嗎? – dasblinkenlight 2012-02-15 16:34:51

+0

構建您的程序以在模擬器中運行,通過單擊編輯器文本空間左側的垂直條上的if([elementName isEqual:@「location」])''行上設置斷點並運行啓用了斷點。一旦你的斷點被擊中,將光標懸停在「位置」變量上以查看其值。 – dasblinkenlight 2012-02-15 16:49:48

回答

0

我覺得有可能是你的問題的原因有兩個:

  1. viewDidLoad之前你解析XML被稱爲,這就是爲什麼你所有的網點是零

  2. 您沒有在Interface Builder中連接它們。

+0

我很確定我的插座連接正確。看到我上面的評論。 – wigging 2012-02-15 16:35:13

+0

那麼我會如何去實施理由1? – wigging 2012-02-15 17:15:37

+0

謝謝我讓它工作。我用'(void)awakeFromNib'替換了'(void)fetchCurrentWeather:(id)sender'方法 – wigging 2012-02-15 23:12:32