LoginSignup
11
11

More than 5 years have passed since last update.

ReactiveCocoa サンプル実装

Last updated at Posted at 2015-01-18

ReactiveCocoaのサンプル実装

基本的にほかのサイトを参考にさせてもらって実装しただけなので先に参考サイトを上げておきます。

参考サイト

http://ios.caph.jp/articles/mvvm-using-reactivecocoa
http://dev.classmethod.jp/smartphone/iphone/reactivecocoaintroduction/

まずはpodのインストール

$ sudo gem install cocoapods
$ pod setup

うまくいかない人は
http://qiita.com/yimajo/items/e89749079d7d5f6cd481
gemのバージョン上げればだいたいOK

適当な場所に新規プロジェクトをxcodeから作成

$ cat Podfile
pod 'ReactiveCocoa'



xxxx.xcodeprojと同じフォルダに上のようなファイルを設置


$ pod install


とすると、xxx.xcworkspaceができるので次回以降はそこからOpenしてください

xxx.xcworkspaceをひらいてViewController.mを以下の内容で編集します。

ViewController.m
#import "ViewController.h"
#import <ReactiveCocoa/ReactiveCocoa.h>

@interface ViewController () <UITextFieldDelegate>
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(100, 100, 120, 40)];
    textField.delegate = self;

    [self.view addSubview:textField];

    RACSignal *signal = RACObserve(textField, text);
    [signal subscribeNext:^(id x) {
        NSLog(@"value changed to %@", x);
    }];

    textField.text = @"sample1";
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

@end

これをビルドして実行すれば、textフィールドへ入力した値を監視してNSLogに落とせることが
確認できます。

ボタンのタップを検出する

さっきのファイルに下記を追加する。

ViewController.m
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(120, 200, 80, 40);
    [button setTitle:@"Push" forState:UIControlStateNormal];
    [self.view addSubview:button];
    button.rac_command =
    [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        NSLog(@"Tapped");
        RACSignal *retSignal = [RACSignal empty];
        return retSignal;
    }];

シミュレータ起動してタップするたびにログが吐かれることがわかると思います。
イチイチメソッド作らなくて済むのがミソ!

  1. sequenceをためす
ViewController.m
    NSArray *charArray = [@"A B C D E F" componentsSeparatedByString:@" "];
    RACSequence *charSequence = charArray.rac_sequence;
    RACSequence *doubleCharSequence =
    [charSequence map:^id(NSString *value) {
        return [value stringByAppendingString:value.lowercaseString];
    }];
    RACSignal *signalFromDoubleCharSequence = [doubleCharSequence signal];

    [signalFromDoubleCharSequence subscribeNext:^(id x) {
        NSLog(@"%@", x);
    }];

実行すれば「A B C D E F」が順に処理されて「Aa Bb ...」と出力されるのがわかると思います。
いかにも関数型ぽい処理ができてます。
for文書かないのが素敵なわけですね。

11
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
11