NSOperationQueue 以及 NSOperation 在 iOS 5 下的問題

來源:互聯網
上載者:User

近期將xcode升級到了4.2,SDK是 iOS5。在 iOS 5 下,以前可以正常工作的 NSOperation,會崩潰。崩潰的原因是:取消隊列中的操作,但是該操作還沒有開始。

解決這個問題的方法是:

        在 start 方法中判斷操作是否已經取消,如果取消,結束操作,沒有取消,再執行操作。

        在 cancel 方法中判斷操作是否正在執行,如果在執行,結束操作,如果沒有,修改操作的isCancelled狀態。

標頭檔:

#import <Foundation/Foundation.h></p><p>@interface FMURLRequest : NSOperation {</p><p> BOOL _isReady;<br /> BOOL _isCancelled;<br /> BOOL _isExecuting;<br /> BOOL _isFinished;<br />}</p><p>- (void)cancel;</p><p>@end<br />

實現檔案:

#import "FMURLRequest.h"</p><p>@interface FMURLRequest ()</p><p>- (BOOL)isReady;<br />- (BOOL)isExecuting;<br />- (BOOL)isFinished;<br />- (BOOL)isCancelled;<br />- (BOOL)isConcurrent;</p><p>- (void)start;<br />- (void)finish;</p><p>@end</p><p>@implementation FMURLRequest</p><p>- (id)init {</p><p> if ((self = [super init])) {<br /> _isCancelled = NO;<br /> _isExecuting = NO;<br /> _isFinished = NO;<br /> _isReady = YES;<br /> }</p><p> return self;<br />}</p><p>- (void)dealloc {</p><p> [super dealloc];<br />}</p><p>#pragma -<br />#pragma mark Operation Management & Super Class Methods</p><p>- (BOOL)isReady {</p><p> return _isReady;<br />}</p><p>- (BOOL)isExecuting {</p><p> return _isExecuting;<br />}</p><p>- (BOOL)isFinished {</p><p> return _isFinished;<br />}</p><p>- (BOOL)isCancelled {</p><p> return _isCancelled;<br />}</p><p>- (BOOL)isConcurrent {</p><p> return YES;<br />}</p><p>- (void)start {</p><p>if (![NSThread isMainThread]) {<br /> [self performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:NO];<br /> return;<br /> }</p><p> [self willChangeValueForKey:@"isExecuting"];<br /> _isExecuting = YES;<br /> [self didChangeValueForKey:@"isExecuting"];</p><p>if ([self isCancelled]) {<br />[self finish];<br />return;<br />}</p><p> // TODO: start operation<br />}</p><p>- (void)finish {</p><p> [self willChangeValueForKey:@"isExecuting"];<br /> [self willChangeValueForKey:@"isFinished"];</p><p> _isExecuting = NO;<br /> _isFinished = YES;</p><p> [self didChangeValueForKey:@"isExecuting"];<br /> [self didChangeValueForKey:@"isFinished"];<br />}</p><p>- (void)cancel {</p><p> [self willChangeValueForKey:@"isCancelled"];<br /> _isCancelled = YES;<br /> [self didChangeValueForKey:@"isCancelled"];</p><p> if ([self isExecuting] == YES) {<br /> // TODO: clean resource<br /> [self finish];<br /> }<br />}</p><p>@end<br />

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.