2015-08-28 80 views
0

剛開始使用ReactiveCocoa並慢慢轉換當前代碼以使用它。ReactiveCocoa倒計時

現在我有一個倒計時日期計時器完成,只是我不知道如何停止計時器倒計時完成後,做完成另一個動作。

NSTimeInterval dateInSecond = 1440855240; 
self.dateUntilNextEvent = [NSDate dateWithTimeIntervalSince1970:dateInSecond]; 
RACSignal *countdownSignal = [[[[RACSignal interval:1 onScheduler:[RACScheduler schedulerWithPriority:RACSchedulerPriorityBackground]] 
           startWith:[NSDate date]] map:^id(NSDate *value) { 

    if([self.dateUntilNextEvent earlierDate:value] == self.dateUntilNextEvent){ 
     //Stop "timer" and call an onComeplete method 
     return @"0"; 
    } 

    NSUInteger flags = NSDayCalendarUnit 
    | NSHourCalendarUnit 
    | NSMinuteCalendarUnit 
    | NSSecondCalendarUnit; 

    NSDateComponents *components = [[NSCalendar currentCalendar] components:flags 
                    fromDate:value 
                    toDate:self.dateUntilNextEvent options:0]; 

    return [NSString stringWithFormat:@"%02ld : %02ld : %02ld : %02ld", 
      (long)[components day], (long)[components hour], 
      (long)[components minute], (long)[components second]]; 

}] deliverOn:RACScheduler.mainThreadScheduler]; 

RAC(self.countdownLabel,text) = countdownSignal; 

任何幫助將appriciated,或只是哪個方向去!

回答

2

您可以使用-takeUntilBlock:當一些謂詞變爲真關閉信號:

@weakify(self); 
RAC(self.countdownLabel, text) = 
    [[[[[RACSignal interval:1 
      onScheduler:[RACScheduler schedulerWithPriority:RACSchedulerPriorityBackground]] 
     startWith:[NSDate date]] 
     takeUntilBlock:^BOOL(NSDate *date) { 

     @strongify(self); 
     return [self.dateUntilNextEvent compare:date] == NSOrderedAscending; 

     }] 
     map:^id(NSDate *date) { 

     // Your NSCalendar/NSString transformation here. 

     }] 
     deliverOn:RACScheduler.mainThreadScheduler]; 

風馬牛不相及:

你也提到你剛開始接觸ReactiveCocoa。對於新用戶來說,其中一個問題是信號由對象保留,但信號由對相同對象進行強引用的塊組成。

在您的-map中,您已參考self。因此,該塊將獲得self的所有權(增加其保留計數),然後當該塊被賦予該信號時,該信號取得該塊的所有權,並且最後當您將信號綁定到self.countdownLabel時,您的self獲得信號。

因此,請注意,在我的-takeUntilBlock我已經使用了@weakify/@strongify技術。請務必閱讀此內容,否則您將在您的代碼中引入保留週期。

+1

令人驚歎的,感謝您的幫助和保留週期問題提示! :) – mario