iOS Learning Note--objective-c Protocol, code block, category

Source: Internet
Author: User

Overview

OBJC's syntax is primarily designed based on Smalltalk, with a number of additional features added in addition to the general object-oriented features, which will focus on some of the commonly used syntax features in OBJC. Of course, although these content and other high-level language naming is not the same, but we can find their shadow, in the article I will compare other languages to introduce, this section of the focus is as follows: (Original address: http://www.cnblogs.com/kenshincui/p/ 3869639.html)

    1. Protocol protocol
    2. Block blocks of code
    3. Category categories
Protocol protocol

To define a set of method specifications using @protocol in OBJC, the class implementing this protocol must implement the corresponding method. Familiarity with object-oriented child shoes all know that the interface itself is the protocol specification for object behavior description. That is, in OBJC @protocol and other language interface definitions are similar, but in OBJC interface keyword has been used to define the class, so it will no longer like C #, Java use interface to define the interface.

Suppose we define an animal's protocol animaldelegate, the person who this class needs to implement this Protocol, see the following code:

AnimalDelegate.h

  animaldelegate.h//  protocol&block&category////  Created by Kenshin Cui on 14-2-2.//  Copyright (c) 2014 Kenshin Cui. All rights reserved.////defines a protocol  //method that must be implemented -(void//Optional Implementation Method -(void) run;-(void) ) say;-(void) sleep; @end          

Person.h

  person.h//  protocol&block&category////  Created by Kenshin Cui on 14-2-2.//  Copyright (c ) 2014 Kenshin Cui. All rights reserved.//<Foundation/Foundation.h>"AnimalDelegate.h"@person:nsobject< animaldelegate>-(void) eat; @end     

Person.m

  person.m//  protocol&block&category////  Created by Kenshin Cui on 14-2-2.//  Copyright (c ) 2014 Kenshin Cui. All rights reserved.//"Person.h"@implementation person-(void) eat{NSLog (@"eating ..."  );} @end     

Here are a few things to note:

    1. One protocol can be extended from another protocol, such as the above animaldelegate extension from NSObject, if you need to extend the middle of multiple protocols using commas separated;
    2. Unlike other high-level languages, the methods defined in the Protocol are not necessarily necessary, and we can set the @required and @optional by keyword, if not set then the default is @required (note that OBJC is weak syntax, Even if you do not implement the required method compile run will not error);
    3. The protocol is implemented by <>, and a class can implement multiple protocols at the same time, separated by commas;
    4. The implementation of the Protocol can only be done on the declaration of the class, not on the implementation of the class (that is, it must be written @interface person:nsobject<animaldelegate> and not written @implementation person< animaldelegate>);
    5. The protocol cannot define attributes, member variables, and so on, but can only define methods;

The fact that the protocol is more useful in OBJC is to constrain a class to implement certain methods, and from an object-oriented point of view the class is not necessarily a natural relationship with the interface, it is probably two things in a completely different sense, which we call the proxy pattern (delegation). This pattern is used extensively in the cocoa framework for separating data from the UI, and basically all protocols end in delegate.

Now suppose you need to design a button, we know that the button is needed to click, in other languages usually introduce the event mechanism, as long as the user subscribed to the Click event, then the click will trigger the execution of this event (this is a way of decoupling between objects: code injection). However, there is no definition of events in OBJC, but proxies are used to deal with this problem. The proxy for the button is defined first in the button, and the proxy (the trigger of the event) must implement some of the methods in the Protocol, and when the button is processed, this method is called if the agent implements the method.

KCButton.h

kcbutton.h//protocol&block&category////Created by Kenshin Cui on 14-2-2.//Copyright (c) 2014 Kenshin Cui. All Rights reserved.//#import<Foundation/Foundation.h>@ClassKcbutton;One protocol can extend another protocol, such as Kcbuttondelegate extending the NSObject protocol@protocol kcbuttondelegate <NSObject> @requiredThe method of @required modification must implement-(void) OnClick: (Kcbutton *) button; @optionalThe method of @optional modification is an optional implementation-(voidvoidinterface  #pragma mark-Attribute  #pragma mark agent Properties, At the same time the contract as an agent must implement the Kcbuttondelegate protocol @property ; #pragma mark-Public method  #pragma void) click; @end     

Kcbutton.m

  kcbutton.m//  protocol&block&category////  Created by Kenshin Cui on 14-2-2.//  Copyright (c) 2014 Kenshin Cui. All rights reserved.//"KCButton.h"@implementation kcbutton-(void) click{NSLog (@"Invoke Kcbutton ' s click Method. " if([_delegate respondstoselector: @selector (OnClick:)]) {[_delegate onclick:self];}} @end      

MyListener.h

  mylistener.h//  protocol&block&category////  Created by Kenshin Cui on 14-2-2.//  Copyright (c) 2014 Kenshin Cui. All rights reserved.//<Foundation/Foundation.h>@Kcbutton; @protocol kcbuttondelegate;@  mylistener:nsobject<kcbuttondelegate>-(void) OnClick: (Kcbutton *) button; @end   

Mylistener.m

  mylistener.m//  protocol&block&category////  Created by Kenshin Cui on 14-2-2.//  Copyright (c) 2014 Kenshin Cui. All rights reserved.//"MyListener.h""KCButton.h"@implementation mylistener-(void) OnClick: (Kcbutton *) button{NSLog (@"Invoke MyListener ' s OnClick method.) The button is:%@. " , button);} @end      

Main.m

main.m//protocol&block&category////Created by Kenshin Cui on 14-2-2.//Copyright (c) 2014 Kenshin Cui. All Rights reserved.//#import<foundation/foundation.h> #import  "KCButton.h"  #import  "MyListener.h" int int ARGC, * argv[]) {@autoreleasepool {Kcbutton * Button=[[kcbutton Alloc]init]; MyListener *listener=[[mylistener Alloc]init]; button. delegate=listener; [Button click]; /* result: Invoke Kcbutton ' s click Method. Invoke MyListener ' s OnClick method. The button is:<kcbutton:0x1001034c0>. */ return 0;}    

We used an example to simulate the click process of a button, a bit similar to the implementation mechanism of events in Java. In this example, we need to pay attention to the following points:

    1. The ID can represent any one of the OBJC object types, and the "< protocol name >" After the type is used to constrain the object as this property must implement the Protocol (note: the object type defined with ID does not need to be "*");
    2. MyListener as the event trigger, it implements the Kcbuttondelegate proxy (without the concept of namespaces and packages in OBJC, usually by prefix class partitioning, "KC" is our custom prefix)
    3. In the. h file if another file class or protocol is used, we can declare it through @class or @protocol, without having to import the file, which can improve compilation efficiency (note that some cases must use @class or @protocol, For example, the Kcbutton class is used in the Kcbuttondelegate protocol declared above in KCButton.h, and kcbuttondelegate is used in the Kcbutton class declaration below this file to form a reference to each other in a file, which Must use @class or @protocol declaration, otherwise the compile phase will error), but in the. m file you must import the corresponding class declaration file or protocol file (if not imported although the grammar check can pass but the compile link will error);
    4. Use the Respondstoselector method to determine whether an object implements a method (note that the method name is not "onclick" but "onclick:" and that the colon is part of the method name);

Attribute (Nonatomic,retain) is not the focus of this article, we will describe it in the next article.

Block blocks of code

In C # Asynchronous programming we often do function callbacks, because function calls are executed asynchronously, if we want one operation to execute after the execution of another function, we can not be programmed in the normal code writing order, because we do not know when the previous method when the end of execution, At this point we often use an anonymous delegate or lambda expression to pass an operation as a parameter. In fact, there are similar methods in OBJC, called blocks. Block is a function body (anonymous function), it is the implementation of OBJC for closures, in the block we can hold or reference local variables (lambda expression), Using block at the same time you can pass an operation as a parameter (not a function pointer in the C language). In the following example we will use block to implement the above click-Listen operation:

KCButton.h

kcbutton.h//protocol&block&category////Created by Kenshin Cui on 14-2-2.//Copyright (c) 2014 Kenshin Cui. All Rights reserved.//#import<Foundation/Foundation.h>@class kcbutton;typedef voidinterface kcbutton:nsobject #pragma mark-Properties  #pragma mark Click Action Properties @property Span style= "color:black;" > (nonatomic,copy) Kcbuttonclick OnClick; //The above attribute definition is equivalent to the following code//@property (nonatomic,copy) void (^ onClick) (Kcbutton *);  #pragma mark-Public method  #pragma void) click; @end     

Kcbutton.m

  kcbutton.m//  protocol&block&category////  Created by Kenshin Cui on 14-2-2.//  Copyright (c) 2014 Kenshin Cui. All rights reserved.//"KCButton.h"@implementation kcbutton-(void) click{NSLog (@"Invoke Kcbutton ' s click Method. " (_onclick) {_onclick (self);}} @end     

Main.m

main.m//protocol&block&category////Created by Kenshin Cui on 14-2-2.//Copyright (c) 2014 Kenshin Cui. All Rights reserved.//#import <Foundation/Foundation.h>#import "KCButton.h"int main (int argc,  const CHAR * argv[]) {Kcbutton *button=[[kcbutton alloc]init]; button.onclick=^ (Kcbutton *btn) {NSLog (@"Invoke OnClick method. The button is:%@. " , BTN); }; [Button click]; /* Result: Invoke Kcbutton ' s click Method. Invoke OnClick method. The button is:<kcbutton:0x1006011f0>. */ return 0;}              

Using block in the above code also implements the button click event, the block summary is as follows:

    1. Block type definition: return value type (^ variable name) (parameter list)( Note that block is also a type);
    2. typedef definition for BLOCK: return value type (^ type name) (parameter list) ;
    3. Block implementation:^ (parameter list) {operation body};
    4. Blocks can read the variables defined outside the block but cannot be modified, if you want to modify then this variable must declare _block decoration;
Category categories

When we do not change the original code to extend other functionality for a class, we can consider inheriting this class for implementation, but in this case it must be defined as a new implementation subclass in order to have the new functionality of the extension. How do you extend a new feature without changing the original class and you don't have to define a new type when you use it? We know that if the extension method can be used in C #, in fact there are similar implementations in OBJC, that is, category category. Using classifications, we can dynamically add new behaviors to existing classes (especially those in the system or framework) in OBJC. In C # The string has a trim () method used to remove the spaces before and after the string, which is especially handy, but there is no such method in OBJC, here we might add a Stringbytrim () method to NSString by Category:

Nsstring+extend.h

  nsstring+extend.h//  protocol&block&category////  Created by Kenshin Cui on 14-2-2.//  Copyright (c) 2014 Kenshin Cui. All rights reserved.//<Foundation/Foundation.h>@nsstring (Extend)-(NSString *) stringbytrim;@ End  

Nsstring+extend.m

  nsstring+extend.m//  protocol&block&category////  Created by Kenshin Cui on 14-2-2.//  Copyright (c) 2014 Kenshin Cui. All rights reserved.//"nsstring+extend.h"@implementation nsstring (Extend)-(NSString *) stringbytrim{    nscharacterset *character= [Nscharacterset whitespacecharacterset];    [self stringbytrimmingcharactersinset:character];} @end  

Main.m

main.m//protocol&block&category////Created by Kenshin Cui on 14-2-2.//Copyright (c) 2014 Kenshin Cui. All Rights reserved.//#import <Foundation/Foundation.h>#import "nsstring+extend.h"int main (int  ARGC, const char * argv[]) {nsstring *[email protected]"Kenshin Cui"; Name=[name Stringbytrim]; NSLog (@"I ' m%@!" , name); //Result: I ' m Kenshin cui! return 0;}                

We can see from the above output that we have successfully removed the spaces at the end of the @ "Kenshin Cui". The classification file name is generally "original class name + classification name", the definition of classification is by adding "(class name)" After the original class name (note the declaration file. h and implementation file. M is the same).

iOS Learning Note--objective-c Protocol, code block, category

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.