2014-10-16 30 views
0

我想實現UITextFieldDelegate textFieldShouldReturn與ReactiveCocoa處理。不幸的是,當我訂閱信號時,subscribeNext塊會運行。UITextFieldDelegate textFieldShould返回與ReactiveCocoa

使用代表團將實施:

- (void)viewDidLoad 
{ 
    ... 
    self.myTextField.delegate = self; 
} 

... 

- (BOOL)textFieldShouldReturn:(UITextField *)textField 
{ 
    if (textField == self.myTextField) { 
     NSLog(@"Let's go!"); 
    } 

    return YES; 
} 

在ReactiveCocoa我也以類似的方式類似的UITextView + RACSignalSupport添加的UITextField類別。

@implementation UITextField (RACKeyboardSupport) 

static void RACUseDelegateProxy(UITextField *self) 
{ 
    if (self.delegate == self.rac_delegateProxy) return; 

    self.rac_delegateProxy.rac_proxiedDelegate = self.delegate; 
    self.delegate = (id)self.rac_delegateProxy; 
} 

- (RACDelegateProxy *)rac_delegateProxy 
{ 
    RACDelegateProxy *proxy = objc_getAssociatedObject(self, _cmd); 
    if (proxy == nil) { 
     proxy = [[RACDelegateProxy alloc] initWithProtocol:@protocol(UITextFieldDelegate)]; 
     objc_setAssociatedObject(self, _cmd, proxy, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 
    } 

    return proxy; 
} 

- (RACSignal *)rac_keyboardReturnSignal 
{ 
    @weakify(self); 
    RACSignal *signal = [[[[RACSignal 
          defer:^{ 
           @strongify(self); 
           return [RACSignal return:RACTuplePack(self)]; 
          }] 
          concat:[self.rac_delegateProxy signalForSelector:@selector(textFieldShouldReturn:)]] 
          takeUntil:self.rac_willDeallocSignal] 
         setNameWithFormat:@"%@ -rac_keyboardReturnSignal", [self rac_description]]; 

    RACUseDelegateProxy(self); 

    return signal; 
} 

@end 

這裏塊被執行,即使是從來沒有按下回車鍵subscribeNext:

- (void)viewDidLoad 
{ 
    ... 
    [self.myTextField.rac_keyboardReturnSignal subscribeNext:^(id x) { 
     Log(@"Let's go with RAC!"); 
    }]; 
} 

我必須使用跳躍:1,以避免這樣的問題:

- (void)viewDidLoad 
{ 
    ... 
    [[self.myTextField.rac_keyboardReturnSignal skip:1] subscribeNext:^(id x) { 
     Log(@"Let's go with RAC!"); 
    }]; 
} 

知道爲什麼有時候是這樣的?

解決方案:

- (RACSignal *)rac_keyboardReturnSignal 
{ 
    RACSignal *signal = [[[self.rac_delegateProxy 
          signalForSelector:@selector(textFieldShouldReturn:)] 
          takeUntil:self.rac_willDeallocSignal] 
         setNameWithFormat:@"%@ -rac_keyboardReturnSignal", [self rac_description]]; 

    RACUseDelegateProxy(self); 

    return signal; 
} 

回答

1

您正在返回立即在defer塊返回的值的信號,當調用textFieldShouldReturn然後concat -ing新值到流。

UITextView+RACSignalSupport.m中的代碼調用reduceEach以便返回從UITextView實例中提取的字符串值。 defer僅用於訂閱時生成的初始值。

基本上,我認爲你根本不需要defer作爲你的用例。