Ce morceau de code:Quel est le problème avec ce code de threads Objective-C pour mon application iPhone?
- (IBAction) getXML {
goButton.enabled = NO;
[self performSelectorInBackground:@selector(parseInBackground) withObject:nil];
}
- (void)parseInBackground {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
xmlParser = [[XMLParser alloc] init];
NSURL *xmlurl = [[NSURL alloc] initWithString:@"http://www.mysite.com/myfile.xml"];
[xmlParser fetchXMLFromURL:xmlurl];
[self performSelectorOnMainThread:@selector(didFinishXMLParsing) withObject:nil waitUntilDone:YES];
[xmlurl release];
[pool drain];
}
- (void)didFinishXMLParsing {
goButton.enabled = YES;
}
déclenche ce code:
- (void)fetchXMLFromURL:(NSURL *)xmlurl {
XMLData = [[NSMutableData alloc] init];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:xmlurl];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection release];
[request release];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
}
Cependant, quand je fais un pas à travers elle dans le débogage, dès qu'il arrive à « }
» en fetchXMLFromURL il retourne à la ligne:
[self performSelectorOnMainThread:@selector(didFinishXMLParsing) withObject:nil waitUntilDone:YES];
et la connexion à l'URL qui va chercher le code XML ne fait est déclenché. Quelqu'un a une idée pourquoi?
Cette version révisée semble fonctionner correctement, quelqu'un peut-il détecter des problèmes potentiels?
- (void)fetchXMLFromURL:(NSURL *)xmlurl {
XMLData = [[NSMutableData alloc] init];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
XMLData = [NSData dataWithContentsOfURL:xmlurl];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
[self startParsingXML];
}
- (void) startParsingXML
{
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:XMLData];
xmlParser.delegate = self;
[xmlParser parse];
[xmlParser release];
}
a de nouveau révisé, espérons corriger maintenant
- (void)fetchXMLFromURL:(NSURL *)xmlurl {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
XMLData = [[NSData alloc] initWithContentsOfURL:xmlurl];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
[self startParsingXML];
}
- (void) startParsingXML
{
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:XMLData];
xmlParser.delegate = self;
[xmlParser parse];
[xmlParser release];
}
@Noah Witherspoon Donc, dans le cas d'origine, nous arrivons à la fin de 'fetchXMLFromURL' et de terminer le thread, donc tuer la connexion à l'URL? – conorgriffin
Très probablement, oui. –
A droite, 'fetchXMLFromURL:' retourne immédiatement 'parseInBackground'. Mais voir la réponse de Rob Keniger. –