2011-05-23 126 views
0

我有一个视图控制器是UIViewController的子类,它具有表视图,表视图中的每一行都链接到不同的xml url。 我做了一个解析器类是子类的NSOperation和实现的方法来解析每行作为选择的XML文件,NSOperationQueue避免将视图控制器推入导航控制器堆栈?

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    [tableView deselectRowAtIndexPath:indexPath animated:YES]; 
    [self performSelectorOnMainThread:@selector(pushView) withObject:nil waitUntilDone:NO]; 
    [self performSelectorInBackground:@selector(parseOperation:) withObject:indexPath]; 
} 

- (void)pushView { 
    detailView = [[viewDetailsController alloc] initWithNibName:@"viewDetailsController" bundle:nil]; 
    [self.navigationController pushViewController:detailView animated:YES]; 
} 

- (void)parseOperation:(NSIndexPath *)indexPath { 
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
    self.queue = [[NSOperationQueue alloc] init]; 
    parserClass *parser = [[parserClass alloc] initWithParseUrl:[[self.arrayOfUrls objectAtIndex:indexPath.row]delegate:self]; 
    [queue addOperation:parser]; 
    [parser release]; 
    [pool release]; 
} 

分析器的伟大工程,但在其自定义的委托方法我称之为推视图控制器在导航控制器堆栈顶部,视图控制器将正确初始化,但新视图控制器不会被推入屏幕。

我已经编辑了使用主线程和后台线程的问题,而后台线程正常工作以解析主线程只是初始化并且不推送视图控制器。 问题是什么?

回答

2

您需要在主线程上推视图控制器。使用performSelectorOnMainThread:withObject:waitUntilDone:来调用主线程上的方法。

如果您有可能会推送多个视图控制器,如果视图控制器被压入堆栈而另一个被动画时,您的应用程序将崩溃。在这种情况下,您应该指定animated:NO或收集查看NSArray中的控制器并使用setViewControllers:animated:将它们添加到堆栈。


在回答您的问题更新:你不应该需要通过performSelectorInBackground:withObject:调用parseOperation:,因为它在一个单独的线程创建反正NSOperationQueue将执行的NSOperation。我建议增加一个delegate属性与您的NSOperation子类,并按照这个模式:

MyViewController.m

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    MyParseOperation *parseOp = ... 
    parseOp.delegate = self; 
    [myOperationQueue addOperation:parseOp]; 
} 

// Called by MyParseOperation 
- (void)operationCompletedWithXML:(XML *)parsedXML 
{ 
    // Use parsedXML to create and configure a view controller 
    MyCustomViewController *vc = ... 

    // Animation is OK since only one view controller will be created 
    [self.navigationController pushViewController:vc animated:YES]; 
} 

MyParseOperation.m

// Call this method once the XML has been parsed 
- (void)finishUp 
{ 
    // Invoke delegate method on the main thread 
    [self.delegate performSelectorOnMainThread:@selector(operationCompletedWithXML:) withObject:self.parsedXML waitUntilDone:YES]; 

    // Perform additional cleanup as necessary 
} 
+0

我已经编辑我的代码,如上,但仍然没有工作。我不知道这个代码有什么问题? – Sandeep 2011-05-23 06:24:51

+0

@疯狂-36:看看我更新的答案是否有帮助。 – titaniumdecoy 2011-05-23 18:08:08

+1

是的,这帮了我。我认为这在解析完成后立即推送视图控制器。但是如果我想在选中某行时立即推送视图控制器,该怎么办?我的意思是如果我想推视图控制器和同时解析XML ... – Sandeep 2011-05-25 07:59:47

相关问题