簡體   English   中英

iPhone-從NSOperation返回

[英]iPhone - return from an NSOperation

我正在使用NSOperation的子類來執行一些后台進程。 我希望用戶單擊按鈕時取消操作。

這是我的NSOperation子類的樣子

- (id)init{
    self = [super init];
    if(self){
        //initialization code goes here
        _isFinished = NO;
        _isExecuting = NO;
    }

    return self;
}

- (void)start
{
    if (![NSThread isMainThread])
    {
        [self performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:NO];
        return;
    }
    [self willChangeValueForKey:@"isExecuting"];
    _isExecuting = YES;
    [self didChangeValueForKey:@"isExecuting"];

    //operation goes here
}

- (void)finish{
    //releasing objects here

    [self willChangeValueForKey:@"isExecuting"];
    [self willChangeValueForKey:@"isFinished"];

    _isExecuting = NO;
    _isFinished = YES;

    [self didChangeValueForKey:@"isExecuting"];
    [self didChangeValueForKey:@"isFinished"];
}

- (void)cancel{
    [self willChangeValueForKey:@"isCancelled"];

    [self didChangeValueForKey:@"isCancelled"];
    [self finish];
}

這就是我將此類的對象添加到隊列並監聽KVO通知的方式

operationQueue = [[NSOperationQueue alloc] init]; [operationQueue setMaxConcurrentOperationCount:5]; [operationQueue addObserver:self forKeyPath:@“ operations”選項:0上下文:&OperationsChangedContext];

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (context == &OperationsChangedContext) {
        NSLog(@"Queue size: %u", [[operationQueue operations] count]);
    }
    else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

要取消操作(例如,單擊按鈕),我嘗試調用-cancel,但沒有任何區別。 還嘗試調用-finish,但即使那樣也沒有任何改變。

每當我向隊列添加操作時,隊列大小只會增加。 完成被調用(使用NSLog語句檢查),但是它並沒有真正結束操作。 我還是不太確定自己做對了

有人可以告訴我我要去哪里了嗎?

非常感謝

NSOperation類參考

取消操作不會立即強制其停止正在執行的操作。 盡管尊重所有操作均應遵循isCancelled返回的值,但是您的代碼必須顯式檢查此方法返回的值,並根據需要中止

也就是說,除非您的實現強制執行此方法,否則cancel方法實際上不會取消該操作。 再次,從相關部分

- (void)cancel

此方法不會強制您的操作代碼停止。 而是,它更新對象的內部標志以反映狀態的變化。

您只需要執行以下操作即可:

在您的NSOperation子類中,添加到main方法

 while (! self.isCancelled) {
  [NSThread sleepForTimeInterval:1];
 }

在GUI類中,您需要一個NSOperation子類的實例變量,在管理按鈕的方法中,您將取消NSOperation子類。 例如:

- (IBAction) clickButton: (UIBarButtonItem *) item{
 [myOperation cancel]; 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM