我正在使用 NSXMLParser 从在线 XML 文件中获取信息。我的目标是让一个类进行 XML 解析,另一个类来实现变量。以下是我的项目的代码:
Current.h 和 Current.m
#import <Foundation/Foundation.h>
@interface Current : NSObject {
NSString *curTempF;
IBOutlet NSTextField *textField;
}
@property (nonatomic, copy) NSString *curTempF;
- (void)displayOutlets:(id)sender;
@end
和
#import "Current.h"
@implementation Current
@synthesize curTempF;
- (void)awakeFromNib {
[self displayOutlets:self];
}
- (void)displayOutlets:(id)sender {
[textField setStringValue:curTempF];
}
@end
XmlParser.h & XmlParser.m
#import <Foundation/Foundation.h>
@interface XmlParser : NSObject <NSXMLParserDelegate> {
NSString *urlString;
NSURL *url;
NSMutableString *xmlString;
}
- (IBAction)fetchXML:(id)sender;
@end
和
#import "XmlParser.h"
#import "Current.h"
@implementation XmlParser
- (void)awakeFromNib {
[self fetchXML:self];
}
- (IBAction)fetchXML:(id)sender {
urlString = @"http://api.wunderground.com/api/***/conditions/q/28173.xml";
url = [NSURL URLWithString:urlString];
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
[parser setDelegate:self];
[parser parse];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
if ([elementName isEqual:@"temp_f"]) {
xmlString = [[NSMutableString alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if ([elementName isEqual:@"temp_f"]) {
Current *cTempF = [[Current alloc] init];
[cTempF setCurTempF:xmlString];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
[xmlString appendString:string];
}
@end
当我运行程序时,我收到有关“无效参数不满足:aString”的错误。看起来 IBOutlet 的 setStringValue 不起作用。有什么建议么?