2013-11-26 37 views
0

我有一個只包含類方法的類。通常,我使用這些方法刷新我的應用程序的數據。
這樣,例如,我想要一個TableViewController從定期提到的第一個類中觸發方法。
我還需要的是當我的TableViewController不再顯示時停止這些調用的可能性。延遲對類方法的調用

我現在正在做的可能不是最好的事情:

//myNetworkingClass.h 
+(void)methods1:(type*)param1; 

    --- 
//myNetworkingClass.m 

+(void)methods1:(type*)param1 
{ 
    //asynchronous tasks 
    [[NSNotificationCenter defaultCenter] postNotificationName:@"updateComplete" object:responseObject]; 
} 

//myTableViewController.m 
    - (void)viewDidLoad 
{ 
    //initialization 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateReceived:) name:@"updateComplete" object:nil]; 
    [myNetworkingClass methods1:param]; 
} 
-(void)updateReceived:(NSNotification*)notification 
{ 
    //some task, especially update datasource 
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 10* NSEC_PER_SEC); 
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ 
     [myNetworkingClass methods1:param]; 
    }); 
} 

有使用該3個問題:

  • 一旦添加到主隊列,我無法取消下一次刷新,就像我解僱我的TableViewController時應該這樣做,並導致第二點
  • 由於任務排隊,如果我的TableViewController被解僱,我會有一個無用的電話。
  • myTableViewController是一個泛型類,所以我可以創建這個類的新對象,並且這個類會收到一個不合規的更新通知,並且會導致崩潰。 (注意:他們是不是2 myTableViewController在同一時間)

我應該如何處理這些限制,並寫了一個「整潔男女混合」:對

感謝您的幫助。

編輯

隨着@AdamG的鏈接,我創建了一個的NSOperation:

@interface OperationRefresh : NSOperation 
-(id)initWithArray:(NSArray *)array andDelay:(int)refreshTime; 
@end 

@implementation OperationRefresh 
{ 
    NSArray *paramA; 
    int delay; 
} 
-(id)initWithArray:(NSArray *)array andDelay:(int)refreshTime 
{ 
    self = [super init]; 
    paramA = array; 
    delay = refreshTime; 
    return self; 
} 
-(void)main 
{ 
    @autoreleasepool { 
     NSLog(@"sleeping..."); 
     [NSThread sleepForTimeInterval:delay]; 
     NSLog(@"Now Refresh"); 
     [myNetworkingClass methods1:paramA]; 
    } 
} 
@end 

但我不能夠取消它。下面是我在做什麼:

-(void)updateReceived:(NSNotification*)notification 
{ 
    //some task, especially update datasource 
    refreshOperation = [[OperationRefresh alloc] initWithArray:param andDelay:10]; 

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^{ 
     [refreshOperation start]; 
    }); 
} 


-(void)viewWillDisappear:(BOOL)animated 
{ 
    [[NSNotificationCenter defaultCenter] removeObserver:self]; 
    [refreshOperation cancel]; 
} 

事實上,當我的視野中消失,它仍然在寫「現在刷新」在控制檯中。

回答

2

您應該使用NSOperations,它將允許您取消在後臺運行的操作。

這裏有一個很好的教程:http://www.raywenderlich.com/19788/how-to-use-nsoperations-and-nsoperationqueues

它也更有效率,並會由於後臺任務而使您的應用程序滯後。

UPDATE

要取消你在的NSOperation手動添加取消。您應該在需要取消操作的位置添加此選項(可能在延遲之前和之後)。

if (self.isCancelled){ 
    // any cleanup you need to do 
    return; 
} 
+1

是啊,如果隊列由視圖控制器,當它消失就可以取消隊列中的一切,這樣的呼籲沒有運行資呢。 – Fogmeister

+0

感謝您的幫助。請看看我的編輯 – zbMax

+0

@zbMax我更新了我的答案以迴應您的修改。 – AdamG