2016-04-02 26 views
0

在我的NSOperation的子類後,我設置4個標誌,並且當操作完成它的執行不會被刪除到的NSOperation隊列,它是在開始時加入,這件事情的原因在我的應用程序中有很多問題。 我想,我設置這些標誌的方式是不正確的,請你幫忙吧。因爲我真的花了很多時間來確定這個問題。對象不從NSOperationQueue刪除執行

@property(assign, nonatomic) BOOL isCancelled; 
@property(nonatomic, getter=isExecuting) BOOL executing; 
@property(nonatomic, getter=isFinished) BOOL finished; 
@property(readonly, getter=isAsynchronous) BOOL asynchronous; 

//in initialisation 
- (id)initWithURL:(NSURL*)url andRaw:(NSInteger)row 
{ 
    if (![super init]) 
     return nil; 
    [self setTargetURL:url]; 

    return self; 
} 
//the way I override KVO 
- (BOOL)isExecuting 
{ 
    NSLog(@"Exec"); 
    return (self.defaultSession != nil);//it doesn't work 
} 

- (BOOL)isFinished 
{ 
    NSLog(@"Finished"); 
    return (self.defaultSession == nil); //it doesn't work, so I explicitly set the value 
} 

- (BOOL)isAsynchronous 
{ 
    return YES; 
} 

- (void)cancel 
{ 
    [super cancel]; 
    [self willChangeValueForKey:@"isExecuting"]; 
    [self willChangeValueForKey:@"isFinished"]; 
    self.isExecuting = NO; 
    self.isFinished = YES; 
    [self didChangeValueForKey:@"isFinished"]; 
    [self didChangeValueForKey:@"isExecuting"]; 

    if(self.downloadTask.state == NSURLSessionTaskStateRunning) 
     [self.downloadTask cancel]; 
    [self finish]; 
} 
- (void)finish 
{ 
    [self willChangeValueForKey:@"isExecuting"]; 
    [self willChangeValueForKey:@"isFinished"]; 
    self.defaultSession = nil; //NSURLSession 
    self.isFinished = YES; 
    [self didChangeValueForKey:@"isFinished"]; 
    [self didChangeValueForKey:@"isExecuting"]; 
} 

預先感謝您

編輯: 終於讓我找到了問題 - 這是NSURLSession隊列中。它保持對隊列的強烈引用,並且不允許將它從NSOperationQueue中解除分配和刪除。

回答

2

我也做了同樣的事情,在斯威夫特albiet。

有幾個方面,我已經實現方式不同,如下表所列:)

  • 我已經注意到,我們沒有覆蓋取消(在 異步操作方法。 NSOperation取消 方法的默認行爲是將self.cancelled布爾值設置爲true。
  • self.executing應該只內操作的被覆蓋的start()方法來設置爲true,但不是在init(不知道這港島線造成任何問題)。在start()方法中設置self.executing = true之前,我確保布爾self.cancelled爲false。如果self.cancelled = true,我們應該設置self.finished = true。
  • 另外,我還創建了isExecuting和isFinished性質,我叫willChangeValueForKey和didChangeValueForKey一個「didSet」屬性的觀察者。我不是100%確定如何複製中的OBJ C的didSet行爲(This說要overrride二傳手)

請參考有關「併發」雷Wenderlich視頻教程山姆·戴維斯解釋的NSOperation子類的創建用於異步操作。請注意,它僅適用於訂閱者,並在Swift中進行了解釋。我相信如果你解決了第1點和第2點,你應該看到你的問題得到解決。

+0

謝謝,我會盡量按照你的指示,不幸的是我不是Ray Wenderlich的用戶(。 – Melany

+0

我強烈建議成爲一個,如果可以的話,他們有一些很棒的教程。 .raywenderlich.com /視頻教程 – shrutim

+0

OK也許我會,如果管理這個問題) – Melany