The callback mechanism in the fine number objective-c

Source: Internet
Author: User
Tags call back define function

I. Agreement

The protocol mainly provides interfaces or similar C ++ multiple inheritance functions, and provides a decoration mechanism for classes. A protocol is not built for callbacks, it should represent a set of interoperable conventions.

advantage:

The implementation is simple and easy to understand.
Strong type checking.
Disadvantages:

A strong coupling relationship is established between classes
It may be necessary to save the delegate for a longer period for callback. If the reserved delegate needs to be exclusive, it may cause trouble to the single-piece model and multithreading.
A class can only complete one type of callback through one method. Code logic can be easily grouped into one method.
Most callback uses do not need to be exposed to the outside through the protocol.

Second, use responsesToSelector and performSelector for callbacks.

Utilize the runtime characteristics of OBJC, find the message of the object and call back

advantage:

Good compatibility with OBJC code.
Features such as delayed execution.
Lightweight callback mechanism.
Disadvantages:

The return value generated by the callback can only be of type id, and types such as int will generate errors.
Only two parameters can be passed in. But you can avoid it by creating a parameter class with multiple parameters. At the same time, the return value limitation can also be solved by establishing an input class and an output class. NSInvocation also provides a multi-parameter solution.

If the

[target performSelector: @selector (callback)];

To establish a callback method, you need to establish a convention for the callback message name of the class, and the callback message name is exclusive, that is, a class can only call back with this message name.

If a callback is established through an external SEL

[target performSelector: sel];

Or external callback

[target performSelector: NSSelectorFromString (@ "callback")];

Using the Auto Argument Compiler Feature (ARC) produces the warning "performSelector may cause a leak because its selector is unknown"

Using this method to establish a callback, when a message that does not comply with the agreement is passed in, a side effect will continue to run instead of reporting an error. For example, the agreed message has 2 parameters, but the incoming message has only 1 parameter, and the last incoming parameter is masked out according to the order of the parameter agreement. Or the incoming message has 3 parameters, and the extra parameter values are not initialized.

Function pointers

The traditional C language callback mechanism.

advantage:

Lightweight callback mechanism.
Only return values and parameters are agreed upon, not function names. No parameters, return value restrictions, flexible use.
The compiler provides type checking. (Warning on error)
Disadvantages:

Not compatible with OBJC's message mechanism. Because the message is not the same as in C, the function name corresponds to the function pointer. That is, callbacks can only be made to C functions.
When passing a function pointer that does not conform to the convention, side effects will continue to run instead of error.

Fourth, objc_msgSend

Get the runtime message calls by importing #import <objc / message.h>.

It is defined as

id objc_msgSend (id theReceiver, SEL theSelector, ...)

advantage:

Lightweight callback mechanism.
There are no restrictions on incoming parameters.
Compared to performSelector, no warning is generated when using the auto-argument feature.
The same series of methods support double, struct and other types of return values, but still do not support int return values (can be wrapped using NSNumber to avoid).
Disadvantages:

When a message that does not meet the agreement is passed in, side effects continue to run instead of reporting an error.

Five, IMP

The IMP is similar to the function pointer provided by OBJC. It queries the passed Selector through the methodForSelector method to obtain the entry address of the function.

It is defined as

id (* IMP) (id, SEL, ...)

Compared with ordinary C function pointers, its definition has two mandatory parameter conventions, id and SEL, and the other is no different from function pointers.

advantage:

Lightweight callback mechanism.
An error is reported when a non-compliant message is passed in.
There are no restrictions on incoming parameters. The return value can be obtained by coercion, without type restrictions. Such as:
typedef int (* CBFUNC) (id, SEL, int, int, int); // define function pointer type

  int ret = ((CBFUNC) callback) (self, sel, param1, param2, param3); // cast
The id and SEL here are only the placeholders agreed by the OBJC system, and there is no practical significance in custom callbacks.

Since this stage is actually a function pointer call, it is better to define the function pointer with a typedef and then force the IMP to avoid errors and provide some compile-time protection.

Disadvantages:

Still does not provide compile-time type checking like protocols and function pointers

Six, NSNotificationCenter

NSNotificationCenter is a message mechanism provided by OBJC. It is somewhat similar to the observer pattern, in which callbacks are established by focusing on the messages of interest. NSNotificationCenter provides a low-coupling object communication mechanism, which is especially suitable for one-to-many callbacks without specified objects.

The main method:

1) Get the message center instance (the system has been created, single item mode)

NSNotificationCenter * nc = [NSNotificationCenter defaultCenter];
2) Send a message. (Called when an event occurs)

NSNotificationCenter * nc = [NSNotificationCenter defaultCenter];

[nc postNotificationName: NOTIFY_MSG_UC_COMMON_PLAYER_PLAY // message name (string)

                  object: self // source

                userInfo: nil]; // user dictionary (pass more custom parameters)
3) Registration message

[nc addObserver: self // observer

       selector: @selector (handleNotify_Play :) // callback

           name: NOTIFY_MSG_UC_COMMON_PLAYER_PLAY // listen for messages

         object: nil]; // message source
4) Logout message

[nc removeObserver: self];
5) callback definition

-(void) handleNotify_Play: (NSNotification *) note;
Only one parameter

 NSNotification *

 --Name // message name

 --Object // message source

 --UserInfo // user dictionary
advantage:

The degree of coupling between callback objects is low. You don't have to know each other.
The information passed through the message is unlimited.
Observers can select specific messages, specific objects, or specific messages of specific objects for observation.
Disadvantages:

Lack of timing. When an event occurs, the order of execution of the callbacks is uncertain. Nor can you wait for the callback to finish performing subsequent operations. Solution: 1) Use the traditional callback mechanism. 2) When multi-threaded, NSCondition can be used to synchronize threads. 3) Use more messages. (Excessive use may cause confusion)

Block

Block is a runtime method mechanism provided by OBJC, similar to Javascript's anonymous function. It provides a temporary callback mechanism at runtime.

Declaration of the Block object:

Declare a Block object cb whose parameter is int and whose return value is int.

int (^ cb) (int);
Definitions can also be simplified with typedefs.

typedef int (^ BLOCK_CALLBACK_FUNC) (int);

BLOCK_CALLBACK_FUNC cb =…
Callback function definition:

-(int) handleBlockCallbackFunc: (BLOCK_CALLBACK_FUNC) callback

{

  return callback (10);

}
The callback function uses:

1) Use after assignment

 BLOCK_CALLBACK_FUNC cb =

   ^ (int param)

   {

     NSLog (@ "Block Msg:% d", param);

     return param * 2;

   };

   int ret = [self handleBlockCallbackFunc: cb];
2) Assignment when used

 int ret = [self handleBlockCallbackFunc:

             ^ (int param) {

               NSLog (@ "Block Msg:% d", param);

               return param * 2;

             }];
note:

1) The variables and parameters used by the block object are bound at runtime, so the variables created by the stack space can be used directly without the need to pass parameters. However, the creation of a block object still has a life cycle limit. Therefore, when a block object that is called asynchronously is passed in, it must be a block created in stack space.

Use Block_copy () to copy the block out of the backup, then use Block_release () to release the block. See chapter Using Blocks, Patterns to Avoid

2) Variables declared in stack space are marked as const when bound to a block. Can only read but not write. If you need to write, you need to mark the variable with __block. At this point, the block uses objects copied from the stack to the heap. When the block is out, the objects in the heap are automatically copied back to the stack if the stack is available.

advantage:

The lightest callback mechanism.
Compiler type checking.
Like function pointers, define callback functions flexibly.
Disadvantages:

effectiveness. (The extent of the impact is unclear)
Easily lead to centralized code logic.
Features after IOS4

to sum up:

OBJC does not yet have a perfect lightweight callback mechanism, and can only choose the appropriate mechanism according to the situation.

Simple callback, no need for reuse, no IOS version limitation, block can be used.
Simple callbacks have reuse requirements. You can use performSelector, objc_msgSend, or the callback mechanism of IMP.
When using automatic arguments, try not to use the @Selector passed in by the performSelector callback to prevent warnings.
There are many interoperations between objects, and the objects need to be reused, and protocols can be used.
One-to-many callbacks without specified objects use NSNotificationCenter.
For special applications such as delayed calls, you can use performSelector.

Author: Xi Boer
Link: https://www.jianshu.com/p/a9b3c0bcc337
Source: Jianshu
Copyright belongs to the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.


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.