"Good Programmer's note sharing"--OC advanced syntax

Source: Internet
Author: User

iOS training------My C language notes, look forward to communicating with you!

iOS Development Advanced Syntax classification, expansion, protocol, code block explanation

One: Classification

What is classification Category ?

    • Classification is the complement and extension part of a class
    • Each part of the supplement and extension is classified
    • Classification is essentially part of a class

Definition of classification

    • Classification is also saved as code in the file
    • Category file naming Main class class name + classification class name
    • Classification files are also divided into *.h files and *.m files

*.h file Storage classification of the declaration part of the content

@interface Main Class class name (class name)

Add method declaration

@end

Implementation part of the. m file storage classification

@implementation Main class class name (class name)

Add a method implementation

@end

    • It is not natural to create an instance variable in a taxonomy, nor can it be created from a property.
    • In a taxonomy, you can access the properties of the main class, but you cannot access the instance variables of the main class.

Here is a simple example of use:

. h file

#import "SomeClass.h"


@interface SomeClass (Hello)
-(void) Hello;
@end

. m file#import "Someclass+hello.h"
@implementationSomeClass (Hello)
-(void) hello{
NSLog (@ "name:%@", @ "Icocos");
}
@endwhere Hello is the category name, and if you create a category with Xcode, you need to fill in the name and the name of the class you want to extend. There is also a convention idiomatic the custom, the declaration file and implementation of the file name uniformly adopted "original class name +category" way named. the invocation is also very simple, without pressure, as follows:first, the category declaration file is introduced and then called normally. #import "Someclass+hello.h"

SomeClass * SC =[[someclass alloc] init];
[SC Hello]the execution results are: Name:icocos
 Usage Scenarios for Category:
    • 1. When you define a class, in some cases (such as a change in requirements), you may want to add a method to one or more of these classes.
    • 2. A class contains many different methods that need to be implemented, and these methods need to be implemented by members of different teams
    • 3. When you are working with classes in the base Class library, you might want these classes to implement some of the methods you need.
 with these requirements, the category can help you solve the problem. Of course, there are some issues to be aware of using category
    • 1. Category can access the instance variables of the original class, but cannot add variables, and if you want to add variables, consider creating subclasses from inheritance.
    • 2, category can overload the method of the original class, but it is not recommended to do so, the consequence is that you can no longer access the original method. If you do overload, the correct choice is to create a subclass.
    • 3, and the common interface is different, in the implementation of the classification of the file can not implement all the declared method, as long as you do not call it.
 using the good category can make full use of the dynamic characteristics of objective-c, and write a flexible and concise code.

two. Expand

Second, expand ( extended )

1. Concept

    • Extension is actually a special form of classification, the extension is not a name.
    • Extension can be understood as anonymous category, also need parentheses.

2. How to use

    • A. You can declare an instance variable in an extension, so you can declare a property
    • B. Extensions are usually defined in the . m of the file and cannot be separated.
    • C. Extensions are properties and methods used to declare private

Difference:

    • Classification: Is not declared instance variable, usually public, the file name is usually : "Main Class class name + Class name ."
    • Extension: Is the instance variable that can be declared, is private, the file name is usually : "The main class class name _ extension identity . h", note that the extension has no name.

Distinction Classification and extension

    • 1. All can be declared in the main class using the
    • 2. In general, it is not recommended to write in the main class because the classification cannot create instance changes, which are essentially different from the main class.
    • 3. Extensions are closely linked to the main class and can create instance variables, so it is common to create extensions and main classes together.

Instance code:

. h file

#import <Foundation/Foundation.h>

@interface NSString (Extend)
-(NSString *) Stringbytrim;
@end

. m file

#import "Nsstring+extend.h"

@implementation NSString (Extend)
-(NSString *) stringbytrim{
Nscharacterset *character= [Nscharacterset Whitespacecharacterset];
return [self stringbytrimmingcharactersinset:character];
}
@end

. main file

#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); Results: I ' m Kenshin cui!

return 0;
}

III: Agreement

1. Concept

    • Agreements are rules, and defining an agreement is the equivalent of making rules.
    • Classes in OC can comply with a protocol, and a class that adheres to a protocol is equivalent to having a capability.

2. Syntax

    • @protocal protocol name
    • @required declare the properties and methods that must be followed
    • @optional declaring optional ( can) compliant properties and methods
    • Default @required

@end

3. One class adheres to an agreement

    • [Email protected] Class name ( classification class name): Parent class name < protocol name >
    • B. Implementing the methods declared in the agreement

4. Use a reference to a protocol type to point to an object that implements the protocol or complies with the Protocol

    • id<trprotocol> p = [[Myclass]init];
    • [P ...]; You can send a message to a reference to the protocol and only send the message that the Protocol requires.

5. Inheritance of the agreement

    • The inheritance of the agreement is equivalent to the merger of the agreement.
    • @protocol TRTarena2 <TRTarena>
    • -(void) learn;
    • @end

6. A class can comply with multiple protocols at the same time, separating the protocols with "," separators.

@interface trstudent:nsobject<trtarena,trtarena3>

7. The use of the Protocol is similar to polymorphic, can be used for arrays, parameters, return value type, only the polymorphic return of the object, must have an inheritance relationship, the type of the object returned by the protocol, must have a compliance protocol or implementation protocol.

Instance code:

. h file

@protocol processdataDelegate <NSObject>

Methods that must be implemented

@required
-(void) Processsuccessful: (BOOL) success;
Choose the method of implementation
@optional
-(ID) SubmitOrder: (NSNumber *) OrderID;
@end

The H file containing protocol is introduced in the H file, which is then declared with this protocol, as follows:

@interface testappdelegate:nsobject<processdatadelegate>;

@end

. m file

@implementation Testappdelegate
-(void) Processsuccessful: (BOOL) success{
if (success) {
NSLog (@ "Success");
}else {
NSLog (@ "failed");
}
}
@end

Four: code block

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 (is it remembered the function pointer in C language)

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

    • Block type definition: return value type (^ variable name) (parameter list)( Note that block is also a type);
    • typedef definition for BLOCK: return value type (^ type name) (parameter list) ;
    • Block implementation:^ (parameter list) {operation body};
    • 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;

Instance code:

  • void (^printblock) (NSString *x);
  • Printblock = ^ (nsstring* str)
  • {     
  • NSLog (@"print:%@", str);
  • };
  • Printblock (@"Hello world!" ); 

"Good Programmer's note sharing"--OC advanced syntax

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.