Block data type
Block encapsulates a piece of code that can be executed at any time
A block can be used as a function parameter or as a return value of a function and can have an input parameter or return value itself.
Apple's official recommendation is to use block as much as possible in a multi-threaded asynchronous task set traversal collection sort animation transitions with a lot of
Defining a block variable
void (^myblock) ();
Int (^sunblock) (int, int);
Using block encapsulation Code
^ {
NSLog (@"==========");
};
^() {
NSLog (@"=========");
};
^ (int a, int b) {
return a + B;
};
Block access outside variables
External variables can be accessed inside the Block
The outer local variables cannot be modified by default within the block
Add the __block keyword to the local variable and the local variable can be modified inside the block
Defining block types with typedef
typedef int (^myblock) (int, int); ///You can use this type of Myblock to define the block variable
Myblock Block;
Myblock B1, B2;
B1 = ^ (int a, int b) {
return a + B;
};
Myblock B3 = ^ (int a, int b) {
return a + B;
};
@protocol keywords
Can be used to declare a whole bunch of methods (cannot declare member variables)
As long as a class complies with this agreement, it is equivalent to having all the method declarations in this agreement.
As long as the parent adheres to a protocol, the subclass also adheres to the
Protocol writing format
@protocol Agreement name <NSObject>
Method declaration List
@end
A class adheres to the agreement
@interface Class Name: Parent class < protocol name 1, ...>
@end
Agreement Compliance Agreement
A protocol that complies with another protocol can have all method declarations for another protocol
@protocol Agreement name < Agreement name 1, ...>
Method declaration List
@end
Keywords for method declarations in the Protocol
@required require implementation does not implement there will be warnings (default)
@optionnal Optional Implementation
Base protocol
NSObject is a base class any other class will eventually inherit it
There is also a NSObject-based protocol that declares many of the most basic methods, such as description retain release, and so on.
It is recommended that each new protocol complies with the NSObject base protocol
When defining a variable, limit the object to which the variable is saved to comply with a protocol
Class name < protocol name > * variable name;
id< protocol name > variable name;
nsobject<myprotocol> *obj = [[NSObject alloc] init];
@property (nonatomic, strong) id<myprotocol> obj;
If the corresponding protocol compiler is not followed, the error will be
OBJECTIVE-C block data type @protocol keywords