IOS development protocol usage-informal and formal

Source: Internet
Author: User
ArticleDirectory
    •  
    •  
    •  
Reprint address: http://www.iloss.me /? P = 545

Protocols are divided into informal and formal protocols.

Let's talk about informal protocols.

Although the keyword of the informal protocol in obj-C is interface, this is not the same as the excuse in C.

Recall the previous learned content. When we define a class sample, a sample. H is generated,CodeAs follows:

# Import <Foundation. h>

@ Interface sample: nsobject {

}

-(Void) helloworld;

@ End

It indicates that there should be a method named helloworld in the sample class (Note: It should be mentioned here, rather than necessary)

It is just a gentleman agreement.

If we do not comply with this Convention (that is, do not implement this method) in sample. m, the compiler will give a warning. However, the compilation is successful.

Note: incomplete implementation of Class "Sample". Meaning: The sample class does not fully implement the methods agreed in interface.
This is where the protocol in obj-C is different from the interface in C #: the interface in C # is mandatory and must be implemented; otherwise, compilation will fail, while obj-C will warn during compilation, it can finally be compiled.

 

Formal Agreement(Protocal)
In fact, the informal protocol (Interface) is changed in a way that seems to be correct.
The semantics is more strong: the class that requires the Protocol is required, and the "must" method agreed in the Protocol is implemented. However, it is entertaining that, even if it is known as a formal protocol, the compiler encounters unruly compiling.
Situation, but still gives a warning. (Of course, the formal agreement also has its meaning, which will be mentioned later)
Here we define an IQUERY Protocol

IQUERY. h

 

@ Protocol IQUERY

-(Void) query :( nsstring *) SQL;

@ End

In addition to changing the keyword @ interface to @ protocal, the others are basically unchanged. The following defines a class dbquery and uses this formal protocol.
Dbquery. h

# Import <Foundation/Foundation. h>

# Import "IQUERY. h"

@ Interface dbquery: nsobject <IQUERY> {

}

@ End

Note that dbquery: nsobject <IQUERY> indicates that dbquery inherits from nsobject and implements the IQUERY interface.
Dbquery. m

# Import "dbquery. H"
@ Implementation dbquery
-(Void) query :( nsstring *) SQL
{
Nslog (@ "query is called. SQL: % @", SQL );
}

@ End

Of course, if you do not implement the method query in dbquery. M, you can compile and pass the query, but you will receive a warning.
So far, you may think that protocal and interface are similar concepts. protocal design is purely redundant. In fact, protocal has the following important significance:
Zheng
Protocal can split the method definition in the business to form a separate file, which is consistent with the extraction interface in the traditional OO. If two systems need to be switched
You can develop a protocal that both parties comply with, and then add the protocol file to the project in both systems to implement it. This function is informal Protocol
(@ Interface. (If you do not believe this, you can change IQUERY in nsobject <IQUERY> to interfaces of other classes.
Try to define the name, and the compilation won't work)
In addition, obj-C
In section 2.0, some extensions are made to the formal protocol, allowing the methods in the formal protocol to be marked as "required (@ requied)" and "optional (@ optional)". If the Protocol
The method in is identified as @ optional. Even if the classes using this Protocol do not implement these methods, the compiler will not give a warning. This gives formal agreements more flexibility. Example:

@ Protocol IQUERY
@ Required
-(Void) query :( nsstring *) SQL;
@ Optional
-(Void) helloworld;
@ End

With the @ optional keyword, "informal protocols" can be replaced by "formal protocols" in terms of semantics, in fact, informal protocols in cocoa are gradually replaced by formal protocols marked with @ optional.
If you select nsobject in xcode code and right-click-> jump to definition, you will find that nsobject is actually an interface or protocal.

Select protocal nsobject to continue. The nsobject. h file defines protocal nsobject.

Similarly, you can also see the definition of interface nsobject.

From this point, we can see that the interface nsobject of the informal protocol actually uses the formal protocol protocal nsobject.

That is to say, in the OO world of obj-C, nsobject, the ancestor of all things, is actually a "formal protocol", so all classes derived from nsobject, only one or more protocols are observed.

 

Another topic "generic"

In obj-C, everything is a pointer. In the previous study, we have come into contact with a special type ID, which can be considered as a special pointer: it can point to any type of object. ID, coupled with the formal protocol, can achieve the effect of the C # Generic Type (Note: It is just like it, not like it)

# Import <Foundation/Foundation. h>
# Import "IQUERY. h"

@ Interface dbquery: nsobject <IQUERY> {

}

-(Void) test :( id <IQUERY>) OBJ;
@ End

Note that-(void) test :( id <IQUERY>) OBJ; this indicates that the test method accepts any type of object as a parameter, however, this parameter object must implement the interface IQUERY (it can also be said that this parameter object must use the formal protocol IQUERY ).
Void test (list <IQUERY> OBJ) looks like?

 

Your understanding:

In fact, the Protocol is equivalent to the virtual class in Java interface or C ++.

For example:

First, we declare an agreement.

@ Protocol myprotocol
-(Void) myprotocolmethod;
@ End

 

@ InterfaceTesta
{
Testb<Myprotocol> * pb; // indicates that Class B should support <comply with> myprotocol.
}
@ Interface Testb:Nsobject<Myprotocol> {

}

Now we can see that if we had one thing last night in Testa, we would like to notify testb. We need to implement it through myprotocol. Then we can send a notification to myprotocol through Pb, and testb will receive the message.

The following is an example of implementing callback functions using the protocol)

When compiling Android development, callback is the most common function. Write a callback function by yourself to dynamically load data. After loading the data, use the callback function to notify the front-end page to display the corresponding data interface. Using the protocol in the iPhone can easily implement callback functions, load data in the background, and display the data on the front-end page.

Implement a test view for the displayed text, and then convert the text to the callback function text after 3 seconds of test. The response is as follows:

The implementation code is as follows:

# Import <uikit/uikit. h>
@ Protocol notedelegate // declare the Protocol
// Callback function
-(Void) messagecallback :( nsstring *) string;
@ End

Call Protocol:

# Import <Foundation/Foundation. h>
# Import "notedelegate. H"
@ Interface managermessage: nsobject {
ID <notedelegate> * notedelegate;
}
@ Property (nonatomic, retain) ID <notedelegate> * notedelegate; // @ property pre-compiled command automatically declares the setter and getter methods of attributes.
-(Void) startthread;
@ End

# Import "managermessage. H"
@ Implementation managermessage
@ Synthesize notedelegate;
// Start a thread
-(Void) startthread
{
// Start the thread
[Nstimer scheduledtimerwithtimeinterval: 3
Target: Self
Selector: @ selector (targetmethod :)
Userinfo: Nil
Repeats: No];
}
-(Void) targetmethod :( nsstring *) String
{
If (self. notedelegate! = Nil ){
// Complete the callback function called by the thread
[Self. notedelegate messagecallback: @ "callback function"]; // callback through the Protocol
}
}
@ End

Foreground page implementation:

# Import "iphonedeleteviewcontroller. H"
# Import "managermessage. H"
@ Implementation iphonedeleteviewcontroller
@ Synthesize textview;

// Callback function
-(Void) messagecallback :( nsstring *) String
{
Self. textview. Text = string; // the front-end receives the callback information to textview.
}

-(Void) viewdidload {
[Super viewdidload];
Self. textview. Text = @ "test ";
Managermessage * message = [[managermessage alloc] init];
// Notification Call Protocol
Message. notedelegate = self;
[Message startthread];
[Message release];
}

-(Void) didreceivememorywarning {
[Super didreceivememorywarning];
}

-(Void) viewdidunload {
Self. textview = nil;
}

-(Void) dealloc {
[Self. textview release];
[Super dealloc];
}

@ End

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.