我正在开发一个iPhone应用程序,并且在我的xml解析器上遇到了一些麻烦。我必须检查来自多个XML文件的多个值,但是当XML解析器处于活动状态时,我无法执行任何其他操作。这不是我想要的,因为检查xml必须在后台完成,而不会被注意到。这是我的一些代码,希望它足够了!
appDelegate.datavalues = [[NSMutableArray alloc] init];
for(int i = 0; i < [headarray count]; i++){
NSMutableArray *infoarray = [[NSMutableArray alloc]initWithArray:[headarray objectAtIndex:i]];
NSString *IP = [infoarray objectAtIndex:1];
NSString *Unique = [infoarray objectAtIndex:2];
NSString *Port = [infoarray objectAtIndex:3];
NSString *relay = (NSString *)[infoarray objectAtIndex:4];
NSString *input = (NSString *)[infoarray objectAtIndex:5];
NSLog(@"relay%@",relay);
NSString *urlAddress = [NSString stringWithFormat:@"http://%@:%@/state.xml",IP,Port];
NSURL *url = [NSURL URLWithString:urlAddress];
NSString *authHeader = [NSString stringWithFormat:@"Basic %@",Unique];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval: 3];
[request setValue:authHeader forHTTPHeaderField:@"Authorization"];
//NSURLConnection *connectionResponse = [[NSURLConnection alloc] initWithRequest:request delegate:self];
NSURLResponse *myURLResponse;
NSError *myError;
NSData* myDataResult = [NSURLConnection sendSynchronousRequest: request returningResponse:&myURLResponse error:&myError];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:myDataResult];
XMLParser *parser = [[XMLParser alloc] initXMLParser];
//parser.relay = [infoarray objectAtIndex:4];
//Set delegate
[xmlParser setDelegate:parser];
//Start parsing the XML file.
BOOL success = [xmlParser parse];
之后我检查了一些值,所以我认为没必要显示!
答案 0 :(得分:1)
您可以将与XML相关的代码重构为单独的方法,然后您可以使用Grand Central Dispatch在后台运行该方法:
- (void) startOperation
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_NORMAL, 0), ^{
[self runSomeXMLChecks];
dispatch_sync(dispatch_get_main_queue(), ^{
// This is dispatched on the main queue so that
// you can update the UI. The NSLog is just an example.
NSLog(@"XML check done!");
});
});
}
答案 1 :(得分:0)
查看NSOperation和NSOperationQueue API和/或并发编程指南。 (两者都在Xcode库中。)
来自文档:
NSOperationQueue类调节一组的执行 NSOperation对象。添加到队列后,进行操作 保留在该队列中,直到明确取消或完成 执行任务。队列中的操作(但还没有 执行)是根据优先级和自己组织的 操作间对象依赖性并相应地执行。一个 应用程序可以创建多个操作队列并提交操作 他们中的任何一个。