0

我的应用程序中有一个 UINavigationController,我正在推送视图控制器。在该视图控制器上,有一个预加载器视图,在后台下载和解析数据时显示动画。动画下方是一个按钮,应该将用户重定向到其他视图控制器。

现在,我可以通过弹出视图控制器来完成此操作,因为我需要定向到的视图是当前视图被推送的视图。然而,这里的问题是下载、解析、计时器等。一切都在后台进行。

我需要的功能是让视图控制器在我通过单击按钮弹出 VC 时完全停止工作。

提前致谢。

4

1 回答 1

1

你用什么来运行后台操作?

您可以通过继承 NSOperation 并使用 NSOperationQueue 来运行它来简化后台操作。你只需要释放 NSOperationQueue,iOS 就会自动为你清理。

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/NSOperation_class/Reference/Reference.html

https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/NSOperationQueue_class/Reference/Reference.html

这是一个例子。

@interface MyBackgroundOperation : NSOperation
@end

@implementation MyBackgroundOperation
- (id)init
{
    self = [super init];

    if(self != nil)
    {        
        // stuff that needs to be done at init
    }

    return self;
}

- (void)main
{
    @try
    {
        // run my background operations
    }
    @catch (NSException *e)
    {
        // catch the exception
    }
}

- (void)dealloc
{
    // clean up
    [super dealloc];
}
@end

然后你像这样开始操作

NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];

MyBackgroundOperation *myOperation = [[MyBackgroundOperation alloc] init];
[operationQueue addOperation:myOperation];
[myOperation release];

[operationQueue release];

操作系统将保留该操作直到它完成,以便释放视图控制器不会影响它。然而,如果你想在它已经开始之后停止操作,你将不得不使用一些更花哨的技术,也许是通知或 KVO。

于 2012-09-19T03:16:09.463 回答