The use of the Dark Horse programmer--objective-c--block and the simple introduction of the protocol

Source: Internet
Author: User

Block is an OC extension to ANSI C, using blocks to better simplify OC programming, and many of OC's APIs are dependent on blocks.

First, block

(a), block of the use of the method

The syntax format is as follows:

^ [block return value type] (parameter 1, parameter 2, ...) {}

Must begin with ^, return value types are usually omitted, and void is recommended as a placeholder if there are no formal parameters.

If a program needs to call a block that has already been defined more than once, you should assign the block to a block variable, which defines the syntax format for the block variable as follows:

Block return value type (^block variable name) (parameter type 1, parameter Type 2, ...);

When you define a block variable, you do not need to declare the parameter name, just specify the parameter type. Similarly, if a block variable does not require a formal parameter, void is recommended as a placeholder.

//main.cintMain () {//if the block has no formal parameters, you can omit the following (), and the block variable () cannot be omitted .    void(^myblock) () = ^{NSLog (@"----------------"); NSLog (@"----------------");    }; //use block variables to invoke code inside blockMyblock (); //block with return value, tangible parameter    int(^sumblock) (int,int) = ^(intAintb) {        returnA +b;         }; intc = Sumblock (1,2); return 0;}

(ii), block and local variables

The block can access the value of the local variable, and the value of the local variable is not allowed to be modified when the chunk accesses the value of the local variable. By adding the __block keyword to the local variable, the local variable can be modified inside the block.

//main.cintMain () {intA =Ten; __blockintb = -; void(^block)        (); Block= ^{        //external variables can be accessed inside the blockNSLog (@"A =%d", a); //by default, the outer local variables cannot be modified inside the block//a = 20; //Add the __block keyword to the local variable and the local variable can be modified inside the blockb = -; NSLog (@"B =%d", B);           };    Block (); return 0;}

Second, the agreement

Protocols are used to define the specifications that multiple classes should follow, and the protocol does not provide any implementations. The agreement embodies the design philosophy of standardizing and realizing separation.

The protocol is used to declare a large stack of methods and cannot declare member variables.

As long as a class adheres to this protocol, it is equivalent to having all the method declarations in this agreement

(a), format of the Protocol

@protocol Agreement name < Other protocol name 1, other protocol name 2>
// method declaration list .... @end


(b), the keyword of the method declaration in the agreement

1> @required (default) requires implementation, and if not implemented, a warning is issued

2> @optional does not require implementation

(iii) Type of Compliance Agreement:

@interface class Name: Parent class name < protocol name 1, protocol name 2>@end

//Protocol1.h, inherit the NSObject protocol, and recommend that each agreement comply with the agreement@protocolProtocol1 <NSObject>//@required requires implementation, a warning is issued without implementation, and the default is//@optional does not require implementation- (void) eat; @optional- (void) test3;@end//Protocol2.h@protocolProtocol2 <NSObject>-(void) cry;@end//Person.h, as long as a class complies with a certain agreement, it can have all the method statements in the agreement.//: Inherit parent class//<> Compliance Agreements@interfacePerson:nsobject <Protocol1,Protocol2>@end//person.m@implementation Person- (void) eat{NSLog (@"Person Eat");}- (void) cry{NSLog (@"Person Cry");}@end 

If you need to use protocols to define variables, there are two ways:

nsobject< protocol 1, Protocol 2...> *obj; ID< protocol 1, protocol 2...> *obj;


The attributes declared in the @property can also be used as a restriction to comply with the protocol:

@property (Nonatomic, Strong) class name < protocol 1, Protocol 2...> * attribute name;
ID< protocol 1, protocol 2...> attribute name;

Three, the agent design mode

(a), the design principle of the agent

A class that does not want to implement some methods by itself, defines member variables or properties that implement these methods, and can invoke methods through member variables. The object that this member variable points to is called the proxy object.

(ii), design principles

(1) You have to have a proxy object property

(2) What are the methods of the agent?

(3) Be sure to decouple

(iii) Implementation of the programme

(1) Define a protocol, in which to declare some methods of communication with the agent

(2) has a proxy attribute ID delegate

(3) Let the agent comply with protocol

//TicketDelegate.h to declare some errands .@protocolTicketdelegate <NSObject>//back to Fares- (Double) Ticketprice;//How many tickets are left?- (int) Leftticketsnumber;@end//Agent.h, proxy object@interfaceAgent:nsobject <TicketDelegate>@end@implementationAgent//AGENT.M//number of votes left- (int) leftticketsnumber{// ... Run the cinema in person or on the phone        return 1;}//How much does each ticket cost?- (Double) ticketprice{// ... Run the cinema in person or on the phone    return  +;}@end//NextAgent.h, proxy object@interfaceAgent:nsobject <TicketDelegate>@end@implementationAgent//NEXTAGENT.M//number of votes left- (int) leftticketsnumber{return  -;}//How much does each ticket cost?- (Double) ticketprice{return Ten;}@end//Person.h@interfacePerson:nsobject- (void) Buyticket;//have a proxy attribute//ID represents the proxy's class name casually//but must abide by the Ticketdelegate agreement@property (nonatomic, retain)ID<TicketDelegate>Delegate;@end//person.m@implementation Person//Buy Movie Tickets- (void) buyticket{//Ask the agent to buy tickets for yourself (ask for the fare, ask for the remaining number of tickets)    DoublePrice =[_delegate Ticketprice]; intNumber =[_delegate Leftticketsnumber]; NSLog (@"with the help of the agent, the fare =%f, there are%d tickets left", price, number);}- (void) dealloc{[_delegate release]; [Super Dealloc];}@endintMainintargcConst Char*argv[]) {    //peoplePerson *p =[[Person alloc] init]; //AgentAgent *a = [[Agent alloc] init];//First AgentNextagent *na = [[Nextagent alloc] init];//a second agent//set up agents for peopleP.Delegate=A; //people are going to see a movie[P buyticket]; //set up agents for peopleP.Delegate=na; //people are going to see a movie[P buyticket];    [A release];    [Na release];    [P release]; return 0;}

The use of the Dark Horse programmer--objective-c--block and the simple introduction of the protocol

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.