Reactivecocoa Framework rookie entry--signal (Signal) Detailed lesson five: a summary of RAC usage for beginners

Source: Internet
Author: User
Configuring a RAC Environment

I am accustomed to using Cocoapods to install GitHub Open Source Library, not novice iOS developers are interested to learn.

Want to learn cocoapods classmate recommend Tang Qi predecessors of the article.

Platform:ios, ' 8.0 '
pod ' Reactivecocoa ', ' ~>2.1.8 '

One thing to note here is the issue of the RAC version, since I have not yet learned swift, so I write the program in OC, the latest version of RAC has already supported Swift, but installing the newest version of RAC in OC may not run, So it is recommended that you use the RAC below the 2.5.0 version (specific support for Swift's version may be incorrect, but I quote the 2.1.8 must be OK). using RAC 1.target-action

One of the basic tips for using RAC is to listen to events.

PS: In the development of iOS, we say that the Click event is target-action, contact with the development of iOS people will not be unfamiliar with the uicontroleventtouchupinside, which is pressed and loosened the action. Not only UIButton, but also Uitextfield have a goal-action mode.

Do not 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");
}];

Just two lines of code. He implements a function that listens to the Textfild uicontroleventeditingchanged event and implements the method NSLog when the event occurs.
So we can use this code as a template for using RAC, extrapolate, we can use the RAC method to add the UIButton click event, no longer need to add target.
There's a simpler word for Textfild's text-change listening.

[[Self.textfild rac_textsignal] subscribenext:^ (ID x) {
    NSLog (@ "%@", x);
}];

This is the result of each change in textfild output.

For example, add a gesture 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 part of the specific I do not explain, I believe we can read, do not understand their own write to understand. 2. The Agent

The use of a RAC write agent is limited, and it can only implement proxy methods that return a value of void

First we need to understand why we use RAC to write proxies. A: Simplify the code. Yes, indeed, in order to simplify the code, why should I emphasize this here because I am deeply aware of the merits of RAC in the proxy approach. At first I didn't want to take the time to learn RAC, but my master gave me an example, if there are multiple alertview in a view, each Alertview has many buttons, each button has its own Click event, what should I write. I thought for a moment, not only each button needs to mark, and each alertview also 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 the proxy method.

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 *tuple) {
    NSLog (@ "%@", Tuple.first);
    NSLog (@ "%@", Tuple.second);
    NSLog (@ "%@", Tuple.third);
}];
[Alertview show];

Let's take a look at the RAC statement. @selector refers to the way this event is monitored fromprotocol refers to a dependent agent. Here there is a ractuple, he is equivalent to a collection class, his first,second, and so is the class of various parameters, I here dot alertview the second button output a bit.

2016-01-04 18: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] 1
2016-01-04 18:24:29.115 racstudytest[5003:388870] (NULL)

You can see that Tuple.second is the serial number of the button in Buttonatindex. So for the above example, I can use switch to add methods to each button, so the code looks easier to understand, the aspect of later maintenance.

Of course, the Alertview agent also has simplified code.

[[Alertview rac_buttonclickedsignal] subscribenext:^ (ID x) {
    NSLog (@ "%@", x);
}];

Here the x is the serial number of each button, you can directly deal with the problems I have encountered above. 3. Notice

In our development notice is also a more common function, the main application scenario is a page for data retransmission needs to update model but click Back to the stack will not refresh the return interface data, then you can use the notification to update another page of data, Of course we can also refresh the data in the Viewdidappear method of another page, but that's a digression.

The demo here is what I said above.

First of all, we need to give a notice on a certain page, and here is the basic notice. 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];

On the accepted page we need to add the viewer and accept the array, and our RAC comes in handy.

[[[Nsnotificationcenter Defaultcenter] rac_addobserverforname:@ ' postdata ' Object:nil] subscribeNext:^ ( Nsnotification *notification) {
    NSLog (@ "%@", notification.name);
    NSLog (@ "%@", Notification.object);
}];

When this page is called PostData, he will execute the method in block, of course, the parameters here can be changed to ID x is also possible, where the nsnotification is mainly to emphasize its type. Let's look at the output of the console.

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

Visible, Notification.object is the array we want, of course we can also pass some model. It is worth mentioning that thenotification in the RAC does not require the Remove observer, because in the Rac_add method he has already written the remove. 4.KVO

Most of the KVO in RAC are macro definitions, so the code is very concise, simply Racobserve (target, KeyPath), Target is listening to the target, KeyPath is the attribute value to observe, and here's a very simple example, Output success if Uiscrollview is scrolled.

Uiscrollview *scrolview = [[Uiscrollview alloc] Initwithframe:cgrectmake (0, 0, MB)];
Scrolview.contentsize = Cgsizemake (in);
Scrolview.backgroundcolor = [Uicolor 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 not be more lamented the strength of RAC. Summary

RAC is a lot of things, but I believe this article for everyone to get started still can, here is introduced RAC basic use method, but there are a lot of useful things such as the signal did not introduce, Even in addition to Subscribenext and Subscribecomplete and Subscribeerror, these are my own to save the pit, will be introduced to you later. Also welcome to my blog to see.

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.