Objective-c syntax (8), objective-c syntax

Source: Internet
Author: User
Tags define function

Objective-c syntax (8), objective-c syntax
Block (the data type of oc, which is very common and essentially a c struct)

Similar to inline functions, from the source code layer, there is a function structure, but after compilation, it does not have the function nature. During compilation, similar to macro replacement, use the function body to replace the name of the called Function

Block encapsulates a piece of code that can be executed at any time

A Block can be used as a function parameter or return value, and it can contain an input parameter or return value.

Apple officially recommends using block as much as possible. It is widely used in multithreading, asynchronous tasks, set traversal, set sorting, and animation transfer.

BlocksDefinition:

int (^MySum)(int, int) = ^(int a, int b) {     return a+b;};

Defines a blocks object named MySum. It has two int parameters and returns int. The right side of the equation is the specific implementation of blocks. blocks can access local variables but cannot be modified.

Block is similar to a statement, such as 10;

Int sum = 10; int (^ MyBlock) (int) = ^ (int num) {sum ++; // return num * sum ;};

If you want to modify it, add the keyword :__ block.

_ Block int sum = 10;

Global variables can be accessed and modified.

BlocksComparison with function pointers (similar)

Define function pointer

Int (* myFn )();

Define Blocks

Int (^ MyBlocks) (int, int );

Call function pointer

(* MyFn) (10, 20 );

Call Blocks

MyBlocks (10, 20 );

BlocksValue assignment

Define variables while declaring, and then assign values

int (^MySum)(int,int) = ^(int a,int b) {     return a + b;};

You can also declare the type first with typedef and then define the variable to assign values.

typedef int (^MySum)(int,int);MySum sum = ^(int a,int b) {     return a + b;}; 

What block needs to know
1> how to define block variables (two types)

int (^sumBlock)(int, int);void (^myBlock)();

2> How to Use block to encapsulate code

^(int a, int b) {return a - b;};^() {NSLog(@"----------");};

3> block access to external variables

* The block can access external variables.
* By default, external local variables cannot be modified inside the block.
* Add the _ block keyword to the local variable, which can be modified inside the block.

4> Use typedef to define the block type

Typedef int (^ MyBlock) (int, int); // you can use MyBlock to define the block Variable MyBlock block; MyBlock b1, b2; b1 = ^ (int, int B) {return a-B ;}; MyBlock b3 = ^ (int a, int B) {return a-B ;};
Basic usage of protocol

It is used to declare a lot of methods (member variables cannot be declared), just declaration!

As long as a class complies with this Protocol, it is equivalent to having all the method declarations in this Protocol.

As long as the parent class complies with a certain protocol, it is equivalent to the sub-class also complies

Protocol Compilation

@ Protocol name // method declaration list @ end

A class complies with the Protocol

@ Interface Class Name: parent class <protocol name> @ end

The Protocol has two keywords to control whether a method is implemented (@ required by default). In most cases, it is used for communication between programmers.

  • @ Required: This method must be implemented (if not implemented, the compiler will issue a warning)
  • @ Optional: This method does not have to be implemented

Agreement compliance

  • One protocol can comply with multiple other protocols. Multiple protocols are separated by commas (,).
  • An agreement that complies with other protocols is equivalent to having a method statement in other Protocols
@ Protocol name <protocol 1, protocol 2> @ end
Base protocol
  • NSObject is a base class, the most fundamental and basic class. Any other class will eventually inherit it.
  • In fact, there is also a protocol named NSObject, which is a base protocol and the most fundamental and basic protocol.
  • The NSObject Protocol declares many basic methods, such as description, retain, and release.
  • We recommend that each new protocol comply with the NSObject protocol.
Specify protocol when defining variables
// NSObject-type object, which must comply with the NSCopying protocol NSObject <NSCopying> * obj; // any OC object and comply with the NSCoding protocol id <NSCoding> obj2;

How to create a new protocol in xcode6: The following similar window in the oc file (including creating a category)

Create a. h file because the protocol is used to declare the method. Declare it in the header file.

// MyProtocol. h # import <Foundation/Foundation. h> // defines a protocol named MyProtocol @ protocol MyProtocol <NSObject> // @ required, if it is not implemented, a warning will be issued // @ optional does not require implementation-(void) test4; @ required-(void) test;-(void) test2; @ optional-(void) test3; @ end // MyProtocol2.h # import <Foundation/Foundation. h> @ protocol MyProtocol2 <NSObject>-(void) haha2; @ optional-(void) haha3; @ end // MyPrototol3.h # import <Foundation/Foundation. h> # import "MyProtocol. h "// if one protocol complies with another protocol, it can have all the method declarations of the other protocol @ protocol MyProtocol3 <MyProtocol>-(void) hehe; @ end/* File Name: person. h */# import <Foundation/Foundation. h> @ class Hashiqi; @ protocol MyProtocol2; @ protocol MyProtocol3; // as long as a class complies with a certain protocol, it can have all the method declarations in this protocol //: inherit // <> follow the protocol @ interface Person: NSObject <MyProtocol3, MyProtocol2> @ property (nonatomic, strong) id <MyProtocol2> obj; @ property (nonatomic, strong) hashiqi * dog; @ end/* file name: Person. m */# import "Person. h "# import" MyProtocol2.h "# import" MyProtocol3.h "@ implementation Person-(void) test {}@ end // MyProtocol4.h # import <Foundation/Foundation. h> @ protocol MyProtocol4 <NSObject> @ end/* file name: Dog. h */# import <Foundation/Foundation. h> @ protocol MyProtocol2; @ interface Dog: NSObject <MyProtocol2> @ end/* file name: Dog. m */# import "Dog. h "# import" MyProtocol2.h "@ implementation Dog-(void) haha2 {}@ end/* file name: Hashiqi. h */# import "Dog. h "@ protocol MyDogProtocol <NSObject>-(void) dogTest; @ end @ interface Hashiqi: Dog <MyDogProtocol>-(void) addTest; @ end @ interface Hashiqi (Add) -(void) addTest; @ end/* file name: Hashiqi. m */# import "Hashiqi. h "@ implementation Hashiqi-(void) dogTest {}@ end @ implementation Hashiqi (Add)-(void) addTest {}@ end // Hashiqi + MJ. h # import "Hashiqi. h "@ interface Hashiqi (MJ) @ end // Hashiqi + MJ. m # import "Hashiqi + MJ. h "@ implementation Hashiqi (MJ) @ end // main. m # import <Foundation/Foundation. h> # import "MyProtocol. h "# import" MyProtocol3.h "# import" Person. h "# import" Dog. h "# import" Hashiqi. h "int main () {Person * p = [[Person alloc] init]; p. obj = [[Hashiqi alloc] init]; return 0;} void test () {// NSObject * obj = [[NSObject alloc] init]; // NSObject * obj2 = @" 4324324 "; // The object stored in obj3 must comply with the MyProtocol protocol // NSObject <MyProtocol> * obj3 = [[NSObject alloc] init]; NSObject <MyProtocol> * obj3 = [[Person alloc] init]; obj3 = nil; // id is equivalent to NSObject * id <MyProtocol> obj4 = [[Person alloc] init]; obj4 = nil; // required obj5. The stored object must comply with MyProtocol3 and inherit the Person <MyProtocol3> * obj5 = [[Person alloc] init]; obj5 = nil ;}

Protocol definition
@ Protocol name <NSObject>
// Method declaration list ....
@ End

How to comply with the agreement
1> class Compliance Agreement
@ Interface Class Name: parent class name <protocol name 1, protocol name 2>
@ End

2> agreement compliance
@ Protocol name <other protocol name 1, other protocol name 2>
@ End

3. Keyword of method declaration in the Protocol
1> @ required (default)
Implementation required. If not, a warning will be issued.

2> @ optional
No implementation required, no warning

4. When defining a variable, restrict the objects stored in the variable to comply with a certain protocol.
Class Name <protocol name> * variable name;
Id <protocol name> variable name;
NSObject <MyProtocol> * obj;
Id <MyProtocol> obj2;

If the protocol is not followed, the compiler will warn

5. the attribute declared in @ property can also be used as a protocol-compliant restriction.
@ Property (nonatomic, strong) class name <protocol name> * attribute name;
@ Property (nonatomic, strong) id <protocol name> attribute name;

@ Property (nonatomic, strong) Dog <MyProtocol> * dog;
@ Property (nonatomic, strong) id <MyProtocol> dog2;

6. the Protocol can be defined in a separate. h file or a class.
1> if this Protocol is only used in a class, the protocol should be defined in this class.

2> if this protocol is used in many classes, it should be defined in a separate file.

7. the category can be defined in a separate. h and. m files, or in the original class.
1> generally, they are defined in separate files.
2> the classification defined in the original class only requires reading the syntax

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.