2011-09-02 38 views
1

我已經創建了一個NSOperation的自定義子類,並且覆蓋了main方法。將NSOperation的自定義子類標記爲已終止?

@interface WGTask : NSOperation 
@property(readonly) BOOL isExecuting,isFinished; 
@end 


@implementation WGTask 
@synthesize isExecuting,isFinished; 
- (void)start { 
    ... 
    [self willChangeValueForKey:@"isFinished"]; 
    isFinished=YES; 
    [self didChangeValueForKey:@"isFinished"]; 
    ... 
} 
@end 

但是這段代碼引發了一個EXC_BAD_ACCESS錯誤。刪除[self didChangeValueForKey:@"isFinished"][self willChangeValueForKey:@"isFinished"]可以解決問題,但即使isFinished值正確更新,NSOperationQueue也不會刪除該操作!

回答

2

我的錯。在調用[self willChangeValueForKey:@"isFinished"]之前,我正在調用我的自定義子類的委託方法,其中我自己發佈了該任務。這就是爲什麼我得到了EXC_BAD_ACCESS錯誤,因爲self不存在了。

+0

不得不重新讀這幾次到得到它(這也幫助http://stackoverflow.com/questions/3291834/asihttprequest-dealloc-and-exc-bad-access-problem),但我最終發現我的看法是「自動釋放」,這就是爲什麼我得到我的exc_bad_access。 –

1

不要創建isExecuting等作爲屬性

從文檔:

如果要實現並行操作,則應該重寫此方法來回報您的操作的執行狀態。如果您確實覆蓋它,請確保在操作對象的執行狀態發生更改時爲isExecuting鍵路徑生成KVO通知。有關手動生成KVO通知的更多信息,請參閱Key-Value Observing Programming Guide。

真的,你可能想使用取消的NSOperation的語義

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

您也不妨讀一讀

NSoperation and key value observing

和(如果你使用這些標誌的依賴管理)

NSOperation KVO problem

+0

謝謝你的回答,但刪除所有屬性並覆蓋' - (BOOL)isExecuting'和' - (BOOL)isFinished'似乎不起作用。我仍然遇到EXC_BAD_ACCESS錯誤。也許我忘記了一些東西。我是否必須實施其他一些方法才能使KVO工作?主要問題是當操作終止時操作隊列沒有得到通知。 – Nickkk

+0

這可能會幫助http://stackoverflow.com/questions/7805702/how-to-check-if-nsoperationqueue-is-finished-and-if-any-operation-failed –

相關問題