-2

我对 xml 解析器进行编码以读取 Internet 上的图像,但是当我在 xcode 上编译文件时遇到问题,他说:“线程 1:SIGABRT

这是代码:

查看 Controller.h :

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<NSXMLParserDelegate> {
    IBOutlet UIImageView *imgView;
    NSMutableArray *photos;
}

@end

视图控制器.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

先感谢您!

4

1 回答 1

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];
}
于 2013-03-17T01:10:57.143 回答