After a few blog, record the different interface between the common methods of value-transfer.
This article records the way of broadcasting.
In the design mode of iOS, the notification mode is also one of the important patterns.
Notification literal translation for the notice, actually I think is called the broadcast mode more appropriate.
It is a function of one object to synchronize the operation of multiple objects.
The usage is simple, an object sends out a broadcast, the listener needs to listen to register first, and then select the channel, finished can listen to the broadcast content.
But be aware that before listening, be sure to register first. Otherwise, the broadcast will not accept, that is, the value has changed, does not respond.
Here is a simple demo with the following effect:
The first interface, as listeners, register to listen to the radio.
The second interface, as a broadcast, sends a broadcast.
When the second interface emits a broadcast, the first interface is automatically received.
You can refer to the source code on git:
Https://github.com/colin1994/NotificationTest.git
The specific implementation is as follows:
The first interface, register as an audience, and set the response event after receiving the broadcast:
-(void) viewdidload{ [Super viewdidload];//do no additional setup after loading the view, typically from a nib. We like to listen to Changetheme's radio //register as a radio station CHANGETHEME channel listener nsnotificationcenter *NC = [Nsnotificationcenter Defaultcenter]; To be a listener. Call self recvbcast: function [NC addobserver:self selector: @selector (recvbcast:) name:@ "Changetheme" Object : nil];} This function is automatically called by the System//iOS system to receive Changetheme broadcast will come to automatically call//notify is broadcast all content-(void) Recvbcast: (nsnotification *) notify{ static int index; NSLog (@ "recv bcast%d", index++); Access to broadcast content nsdictionary *dict = [notify UserInfo]; NSString *name = [dict objectforkey:@ "ThemeName"]; Uicolor *c = [dict objectforkey:@ "ThemeColor"]; Self.title = name; Self.view.backgroundColor = C; }
The second interface, send a broadcast
-(Ibaction) Btnclick: (ID) sender{ //Get the iOS system's only global broadcast Notification Center nsnotificationcenter *NC = [Nsnotificationcenter Defaultcenter]; Set the broadcast content NSString *name = @ "Set color"; Uicolor *color_ = [Uicolor redcolor]; Nsdictionary *dict = [nsdictionary dictionarywithobjectsandkeys: name, @ "ThemeName", color_, @ "ThemeColor", NIL]; Encapsulate content into a broadcast send broadcast to IOS system //Changetheme channel [NC postnotificationname:@ "Changetheme" Object:self Userinfo:dict] ; }