Recognize the three common callback modes for iOS.
Proxy mode is the most common mode of communication in iOS, and proxies are almost ubiquitous.
Here is an array where we first pass the array to the other methods through the proxy method.
Set up protocols and methods
- @protocol callbackdelegate;
- @interface Viewcontroller:uiviewcontroller
- @property (Weak, nonatomic) id<callbackdelegate> delegate;
- @end
- @protocol callbackdelegate <NSObject>
- -(void) Showarraywithdelegate: (Nsarray *) array;
- @end
@interface Viewcontroller () <CallBackDelegate>
Click the button to pass an array to display it
- -(Ibaction) Delegatecallback
- {
- Nsdictionary *dict = @{@ "array": @[@ "Chelsea", @ "MUFC", @ "Real Madrid"]};
- Nsarray *array = dict[@ "Array"];
- [Self.delegate Showarraywithdelegate:array];
- }
Called, displays
- -(void) Showarraywithdelegate: (Nsarray *) array
- {
- _outputlabel.text = array[2];
- }
The most important is also the most easy to ignore, is to set the point of delegate.
Screen display after completion
Using notification hubs
Notification hubs can be used without setting up proxies, but you need to set up observers and remove observers.
Code
- -(Ibaction) CallBack
- {
- Nsdictionary *dict = @{@ "array": @[@ "Chelsea", @ "MUFC", @ "Real Madrid"]};
- Nsarray *array = dict[@ "Array"];
- [[Nsnotificationcenter Defaultcenter] postnotificationname:@ "outputarraynotification" Object:array];
- }
Registering and removing the viewer
- -(void) Viewwillappear: (BOOL) animated
- {
- [Super viewwillappear:animated];
- [[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (outputwithnote:) name:@ " Outputarraynotification "Object:nil";
- }
- -(void) Viewdiddisappear: (BOOL) animated
- {
- [Super viewdiddisappear:animated];
- [[Nsnotificationcenter Defaultcenter] removeobserver:self name:@ "outputarraynotification" object:nil];
- }
Show
- -(void) Outputwithnote: (nsnotification *) anotification
- {
- Nsarray *receivearray = [Anotification object];
- _outputlabel.text = receivearray[0];
- }
Block
What is block: The blocks syntax from the C declarator to the Objective-c
Block codes pass various content in the form of closures, which can be code, which can be an array of everything. Block code is very convenient to unify the code in different places, making it more readable.
See how this is done with array passing.
typedef void (^arr_block) (Nsarray *array);
- -(void) Showarrayusingblock: (Arr_block) Block
- {
- Nsdictionary *dict = @{@ "array": @[@ "Chelsea", @ "MUFC", @ "Real Madrid"]};
- Nsarray *array = dict[@ "Array"];
- Block (array);
- }
Call method, display
- -(Ibaction) Blockcallback
- {
- [Self showarrayusingblock:^ (Nsarray *array) {
- _outputlabel.text = array[1];
- }];
- }
>
Three ways to recall common iOS