我编码一个xml解析器来读取互联网上的图像,但是当我在xcode上编译我的文件时遇到了问题 他说:“线程1:SIGABRT
以下是代码:
查看Controller.h:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<NSXMLParserDelegate> {
IBOutlet UIImageView *imgView;
NSMutableArray *photos;
}
@end
viewController.m:
#import "ViewController.h"
@implementation ViewController
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void)viewDidLoad
{
[super viewDidLoad];
photos = [[NSMutableArray alloc] init];
NSXMLParser *photoParser = [[[NSXMLParser alloc] initWithContentsOfURL: [NSURL URLWithString:@"http://davylebeaugoss.free.fr/Sans%20titre.xml"]] autorelease];
[photoParser setDelegate:self];
[photoParser parse];
NSURL *imageURL = [NSURL URLWithString:[photos objectAtIndex:0]];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
[imgView setImage:image];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI: (NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if ( [elementName isEqualToString:@"photo"])
{
[photos addObject:[attributeDict objectForKey:@"url"]];
}
}
@end
提前谢谢!
答案 0 :(得分:1)
NSURL *imageURL = [NSURL URLWithString:[photos objectAtIndex:0]];
是你的问题。
[photoParser parse];
是异步的,这意味着在调用objectAtIndex:0
时它不完整。
在引用数组之前,您需要等到解析完成。方法
- (void)parserDidEndDocument:(NSXMLParser *)parser
。拨打电话,在那里引用photo
数组。
- (void)viewDidLoad
{
[super viewDidLoad];
photos = [[NSMutableArray alloc] init];
NSXMLParser *photoParser = [[[NSXMLParser alloc] initWithContentsOfURL: [NSURL URLWithString:@"http://davylebeaugoss.free.fr/Sans%20titre.xml"]] autorelease];
[photoParser setDelegate:self];
[photoParser parse];
}
- (void)parserDidEndDocument:(NSXMLParser *)parser {
NSURL *imageURL = [NSURL URLWithString:[photos objectAtIndex:0]];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
[imgView setImage:image];
}