OBJECTIVE-C Programming Full Solution-No. 04 Chapter object type and dynamic binding

Source: Internet
Author: User
Tags inheritance require

Chapter No. 04 Types and dynamic binding of objects

An important feature of OBJECTIVE-C is its dynamic nature, which describes the dynamic type of objective-c, dynamic typing, and dynamically binding.


4.1 Dynamic Binding

4.1.1 What is dynamic binding

The messages in the Objective-c are bound at run time. The runtime system first determines the type of the recipient (dynamic type recognition), then selects the appropriate method execution based on the message name in the method list of the class, and if it is not found, go to the parent class to continue searching, and if it has been found that NSObject has not found the method to invoke, it will report an error that does not recognize the message.

Dynamic binding refers to the ability of a program to determine the properties of an object and to require a corresponding message when it executes.


4.1.2 Polymorphism

In object-oriented programming theory, polymorphism (polymorphism) refers to different execution results when an instance of a class that does not have a different function is the same. That is, when objects of different classes receive the same message, different results can be obtained.

polymorphic [ˌpɒlɪ ' mɔ:fɪk] adj. polymorphic, polymorphic, multi-morphological; Poly-Crystalline type

polymorphism [ˌpɒlɪ ' mɔ:fɪzəm] n. Multi-type phenomenon, polymorphism;  Multi-machine combination form; Multi-shape Sex

Prism |ˈprɪzəm| Noun prism

Polymorphism is an important feature of object-oriented programming, which greatly enhances the flexibility and extensibility of software.

For example, if you are using process-oriented thinking, you may need to add a branch to each additional processing, and you may need to increase the processing in all relevant places. Using polymorphism, however, can greatly reduce the likelihood of a similar situation, and may only require a single additional class.


4.2 Classes as types

4.2.1 The class as a type

We can use a defined class as the type of the object. such as NSObject *object;


4.2.2 Null pointer nil

What happens if you send a message to the nil variable. Although this notation is completely valid, the runtime does not have any effect and the message is not sent.

Here's an example:

if (val = [list entryforkey: "NeXT])! = nil)

{

[Val increment]; Increment |ˈɪŋkrəmənt| noun increase, add value

}

Send a message to the nil variable, the message will not be sent, so the above program is equivalent to the following program.

val = [List entryforkey: "NeXT"];

[Val increment];


The second formulation, while making the program more concise, makes the program more difficult to understand. Because the program is meant to be nil when the return value does not do any processing. In addition, this type of writing also brings a variety of errors, such as the following procedure, if you are not careful.

if (val = [list entryforkey: "NeXT"])! = nil)

{

[Val setvalue:n++];

}

Although Val is nil the message will not be sent, but it does not mean [Val setvalue:n++] will not be executed. If val! = nil is omitted from the above code, the n++ will still be executed, which is different from the "short circuit" in the judgment statement.

So, if a message is sent to nil, what is the return value of the message? In general, if the return value of the method corresponding to the message is an object, nil will be returned, or null if the return value of the method corresponding to the message is a pointer type, or 0 if the return value of the corresponding method of the message is an integer type. If the type of the return value is a type other than these types, such as a struct or a real number, the return value will be undefined;

typedef struct

{

int one;

int;

} myteststruct;


-(Myteststruct) Structtestfunc

{

Myteststruct result = {n};

return result;

}


Test = nil;

Myteststruct mystruct = [Test structtestfunc];

NSLog (@ "%d,%d,%lu", Mystruct.one,mystruct.two,sizeof (MyStruct));//0,0,8

NSLog (@ "%d,%d,%lu", [Test structtestfunc].one,[test structtestfunc].two,sizeof ([Test structtestfunc]);//0,0,8



4.2.3 Static type checking

Although the ID data type can be used to store any type of object in Objective-c, in most cases we declare a variable as an object of a particular class, which is known as a static type. When using a static type, the compiler can perform type checking at compile time if the type does not meet a warning prompt.

In objective-c, the ID type is a common data type, similar to the C language (void*), which can be used to store objects of any class. The real advantage of this type of data during program execution is that the use of ID types combined with polymorphism allows for greater flexibility and scalability of the program. However, the flexibility of the program, but also to pay a price, the compiler does not check the ID type of variables, which will cause the program more error-prone.

In some complex programs, when you use coercion type conversions, you must also be aware of the type, or you will throw a run-time error.

For NSObject objects, even if a cast is coerced, the actual execution of the method is determined by the type of the object.


Summary of 4.2.4 static type checking

(6) to determine which class the method is executed, do not look at the type declared by the variable, but the type of the variable when it is actually executed.

(7) The ID type is not a (nsobject*) type, and there is no inheritance relationship between the ID type and other classes.


The polymorphism of C + + and Java is based on the class hierarchy, and the subclasses can override the methods in the parent class to implement polymorphism. This type of language is not capable of implementing polymorphism that does not have an inheritance relationship, which can be achieved by combining ID types in OC.


4.3 Type definitions in programming

4.3.1 When the signature is inconsistent

Message selector does not contain information about the type of parameters and return values, the message selector and these type information are combined to form a signature (signature), and the signature is used to mark a method at run time. The definition of a method in an interface file is also called a signature.

Nsarray * Arry = @[@1,@2];

[Self Signature: (NSString *) Arry number:2];

-(void) Signature: (nsstring*) str number: (Nsinteger) num

{

NSLog (@ "%@,%p,%u", str,str,num);

/*

2016-06-01 17:12:53.207 test[1153:80130] (

1,

2

), 0x7d276fa0,2

*/

}

Cocoa provides class nsmethodsignature, which records information such as the number of parameters of a method, parameter types, and return value types, in an object-oriented manner. An instance of this class is also called a method signature.

Overloading (over loading) refers to a function, operator, or method definition that has a variety of functions and, depending on the situation, chooses the appropriate function.

OC is a dynamic language, and the type of the parameter is determined at run time, so it is not supported to invoke overloads of different functions depending on the parameter type. OC can use dynamic binding to allow the same message selector to perform different functions to implement overloading.


4.3.2 Declaration of the class

The compiler instructs @class to tell the compiler that a symbol is a class name. This notation is called the pre-declaration of the Class (forward declaration)

Class instruction can be followed by a number of classes at a time, with the "," number split, with ";" to indicate the end. A predecessor declaration can also be declared multiple times. Such as:

@class Nsstring,nsarry,nsmutablearry;

@class Volume;

By using @class, you can increase the overall compilation speed of the program. However, it is important to note that if you want to use a specific member or method of the original class in the newly defined class, you must introduce the original class's header file.

Another benefit of @class is that when multiple interfaces have nested definitions of classes, if only the header files that contain each other cannot be resolved, only the predecessor declarations of the classes can be resolved.


4.3.3 examples of forced type conversions

Although the ability to force type conversions is powerful, it makes the compiler's type checking meaningless, so use as little as possible. Have to use the case, to rethink the design is reasonable.


Data encapsulation of 4.4 instance variables

4.4.1 access rights for instance variables

ClassA.h

//

ClassA.h

Test

//

Created by Ranzhou on 16/6/1.

COPYRIGHT©2016 year Ranzhouee. All rights reserved.

//


#import <Foundation/Foundation.h>


@interface Classa:nsobject

{

NSString *a_default; Default is protected

@public

NSString *a_public;

@protected

NSString *a_protected;

@private

NSString *a_private;

}

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.