简体   繁体   中英

ReactiveCocoa with MVVM

i'm very new to this reactive programming. I'm obviously missing a link here.

Ok, so in my view controller at the moment, I have

- (void)viewDidLoad {
    [super viewDidLoad];

    viewModel = [[ViewModel alloc]init];

    [RACObserve(viewModel, string) subscribeNext:^(NSString* string){
         NSLog(@"%@", viewModel.string);
    }];

    // This fires the NSLog
    viewModel.string = @"Test12345";

    // This doesn't
    [viewModel test];
}

[viewModel test] is...

-(void) test{
    _string = @"Test";
 }

Am I approaching this incorrectly? I thought this would work.

Thanks, Ben.

There's a few issues in your code that your own answer has covered, but the reason that you're not getting a next signal is that you're not setting the string by using self.string , instead you're directly accessing the class' variable as _string .

Properties are actually Objective-C methods that are cleverly hidden from us, when you call self.string = @"Test"; , what's actually happening is the automatically created setString: method of your class is being called, and its default behaviour is to set _string to the newly passed value.

The reason why RAC needs you to do this is that _string is just a normal variable and RAC has no way of knowing that this variable has changed. When you use self.string , RAC can get notifications from the runtime that the setString: method was called via something known as Key-Value Observation.

Wasn't that far off...

[RACObserve(viewModel, string) subscribeNext:^(NSString* string){
     NSLog(@"%@", viewModel.string);
 }];

just needs to be

[RACObserve(self, viewModel.string) subscribeNext:^(NSString* string){
     NSLog(@"%@", string);
}];

AND

[viewModel test];

becomes

[self.viewModel test];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM