Learn RAC-a summary of RAC usage for novice viewing (GO)

Source: Internet
Author: User

Original: http://www.jianshu.com/p/ff79a5ae0353

What is RAC?

Almost every article that introduces RAC begins with this problem. This article is for beginners (including myself) to see, so this problem is not to be ignored.

Simply put, RAC is a third-party library that can greatly simplify your code process.

Officially, Reactivecocoa (which is referred to as RAC) is a new framework for iOS and OS X developed by GitHub Open source. RAC features functional programming and responsive programming.

Why should we learn RAC?

In order to improve our development efficiency. RAC can greatly simplify code when it is developed in certain situations, and is safe and reliable at the moment.

Configuring the RAC Environment

I'm used to using Cocoapods to install the Open Source Library on GitHub, and no novice iOS developers will be interested to learn.

Want to learn Cocoapods's classmates recommend Tang Qi predecessors of the article.

platform:ios, ‘8.0‘pod ‘ReactiveCocoa‘,‘~>2.1.8‘

One thing to note here is the version of RAC, because I have not learned swift, so I wrote the program with OC, the latest version of the RAC has supported Swift, but the OC program installs the most recent edition of RAC may not run up, It is recommended that you use a RAC below the 2.5.0 version (specifically supported for Swift, but the 2.1.8 I quoted is definitely not a problem).

Using Rac1.target-action

The most basic way to get started with RAC is to listen to events.

PS: In the development of iOS, what we call the Click event is actually target-action, the person who has contacted the development of iOS will not be unfamiliar with uicontroleventtouchupinside, this is the action that is pressed and released. Not only UIButton, but also Uitextfield has a target-action mode.

Don't forget to refer to the header file before use ~

#import <ReactiveCocoa/ReactiveCocoa.h>

The next step is the most critical RAC code.

[[self.textFild rac_signalForControlEvents:UIControlEventEditingChanged] subscribeNext:^(id x){ NSLog(@"change");}];

That's just two lines of code. He implements a function that listens to the Textfild uicontroleventeditingchanged event and implements the method when the event occurs NSLog .
So we can use this code as a template for RAC usage, extrapolate, after the UIButton click event we can use the RAC method to add, no longer add Target .
A simpler notation for textfild text change listening

[[self.textFild rac_textSignal] subscribeNext:^(id x) { NSLog(@"%@",x);}];

This is the result of every change in textfild output.

Another example is to add a gesture action to one of our labels, and we can do it with a simple RAC code.

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];[[tap rac_gestureSignal] subscribeNext:^(id x) {    NSLog(@"tap");}];[self.view addGestureRecognizer:tap];

This paragraph specific I will not explain, I believe that we can understand, do not understand their own writing to understand.

2. Agent

It is limited to write proxies with RAC, it can only implement proxy methods that return a value of void

First, we need to understand why we write proxies with RAC. Answer: Simplify the code! Yes, indeed, in order to simplify the code, why I want to emphasize this here, is because in the proxy method I deeply feel the advantages of RAC. At first I was not willing to take the time to learn RAC, but my master gave me an example, if a view has multiple alertview, each alertview has a number of buttons, each button has its own Click event, how should I write? I think about it, not only each button need to mark, and each Alertview to mark, and then to the agent click event Riga various methods, the code is smelly and long. So let's see how RAC writes proxy methods.

Uialertview *alertview = [[Uialertview Alloc] Initwithtitle:@ "RAC" message:@ "RAC TEST" delegate:Self Cancelbuttontitle:@ "Cancel" Otherbuttontitles:@ "other", nil]; [[self rac_signalforselector: @selector (Alertview: Clickedbuttonatindex:) fromprotocol: @protocol (uialertviewdelegate)] subscribenext:^ (RACTuple *< Span class= "Hljs-title" >tuple) {nslog (@ "%@", Tuple.first); nslog (@ "%@", Tuple.second); Span class= "hljs-built_in" >nslog (@ "%@", Tuple.third);}]; [Alertview show];               

Let's look at the statement for RAC. Refers @selector to the method of monitoring the event fromProtocol refers to a dependent agent. There is a ractuple in the block, he is equivalent to a collection class, he is the following first,second and so is the parameters of the class, I click here Alertview the second button other output a bit.

2016-01-0418:24:29.114 racstudytest[5003:388870] <uialertview:0X7FF260C90C70; frame = (0 0; 0 0); Layer = <calayer: 0x7ff260c91030>>2016-01-04 18:24:29.115 racstudytest[5003:388870] 12016-01-04 Span class= "Hljs-number" >18:24:29.115 RACStudyTest[5003:388870] (null)        

You can see the tuple.second number of the button in the Buttonatindex. So for the example above, I can use switch to add methods to the various buttons, so that the code looks easier to understand, aspects of post-maintenance.

Of course, the Alertview agent also has simplified code.

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

The x here is the serial number of each button, which can deal directly with the problems I have encountered.

3. Notice

Notice in our development is also a more commonly used function, the main application scenario is a page for data retransmission needs to update the model but when the return to the stack will not refresh the return interface data, you can use the notification to update the data of another page, of course, we can also be on the other page ViewDidAppear method to refresh the data, but that is an off-topic.

The demo here is what I said above.

First of all, in a page we need to give notice, here is the most basic notice of the wording. Sends a notification named PostData and transmits an array of DataArray.

NSMutableArray *dataArray = [[NSMutableArray alloc] initWithObjects:@"1", @"2", @"3", nil];[[NSNotificationCenter defaultCenter] postNotificationName:@"postData" object:dataArray];

Our RAC comes in handy when we need to increase the observer and accept the array on the accepted page.

[[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"postData" object:nil] subscribeNext:^(NSNotification *notification) { NSLog(@"%@", notification.name); NSLog(@"%@", notification.object);}];

When this page hears the notice named PostData, he will execute the method in block, of course, the parameter is changed id x to be also possible, here uses nsnotification mainly to emphasize its type. Let's look at the output of the console.

2016-01-04 20:10:52.274 RACStudyTest[5918:439077] postData2016-01-04 20:10:52.275 RACStudyTest[5918:439077] (1,2,3)

As you can see, Notification.object is the array we want, and of course we could pass some model. It is worth mentioning that thenotification in the RAC is not remove observer required because in the Rac_add method he has written remove.

4.KVO

RAC KVO Most are macro definitions, so the code is very concise, simple is racobserve (target, keypath) This form, target is the listener target, KeyPath is to observe the value of the property, Here is a very simple example of the output success if the Uiscrollview scrolls.

uiscrollview *scrolView = [[ Span class= "hljs-built_in" >uiscrollview alloc] initwithframe:cgrectmake (0, 0, 200, 400)]; Scrolview.contentsize = cgsizemake ( 200, 800); Scrolviewuicolor greencolor];[ self.view Addsubview:scrolview]; [Racobserve (Scrolview, Contentoffset) subscribenext:^ (id x) { nslog (@ "Success");}];       

If you take a good look at the kvo of the writing will be more exclamation of the strong RAC?

Summarize

RAC a lot of things, but I believe this article for everyone to get started or can, here is the basic use of RAC, but there are many useful things such as the signal is not introduced, Even in addition to Subscribenext and Subscribecomplete and Subscribeerror, these are I give myself to leave a hole, will also post to you.



Wen/barassin (Jane book author)
Original link: http://www.jianshu.com/p/ff79a5ae0353
Copyright belongs to the author, please contact the author to obtain authorization, and Mark "book author".

Learn RAC-a summary of RAC usage for novice viewing (GO)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.