Objective-C 2.0 with cocoa Foundation-4, inherited

Source: Internet
Author: User
ArticleDirectory
    • 4. Inheritance
4. Inheritance

This series of lectures has a strong correlation. If you are reading this article for the first time and want to better understand the content of this chapter, I suggest you read it from Chapter 1 of this series of lectures, click here.

In the previous chapter, I introduced the basic structure, definition, and Declaration methods of classes in objective-C. We know thatProgramWhich has a very important requirement:CodeOne of the important methods to reuse code is inheritance. In this chapter, we will carefully analyze the concept of inheritance and the methods used. If you have other object-oriented languages, you should be familiar with the content of this chapter.

 

4.1 execution results of programs in this Chapter

In this chapter, we will repeat part of the code in Chapter 3rd. In Chapter 3rd, we constructed a cattle class. In this chapter, we need to use the cattle class. Then, based on the cattle class, we need to construct a subclass called the bull class. In the bull class, We append an instance variable named skincolor. We will also append two instance methods, getskincolor and setskincolor. Then we need to change our main function, and then let our bull make an important speech in the main function. Chapter 4 execution results of the program are as follows:

Figure 4-1. execution results of the program in this Chapter

4.2. Implementation steps

Step 1: Create a project named 04-Hello inheritance according to the method described in Chapter 2. If this is the first time you read this article, please refer to Chapter 2 here.

Step 2: Move the mouse over "Source" in the project browser, select "add" in the pop-up menu, and select "exsiting Files" in the sub-menu, as shown in 4-2.

 

Figure 4-2: append a file to the Project

Step 3: In the file selection menu, select the project folder "03-Hello class" in Chapter 3rd, open the folder, and use the mouse and the command key of the Apple Computer, select the zewen "cattle. H and cattle. m, and then press the Add button, as shown in 4-3. If you have not downloaded the code in Chapter 3rd, click here to download it.

 

Figure 4-3 select a file

Step 4: In the option dialog box of the append object, change the single sequence of "Copy items into destination group's folder (if needed)" to the selected state. This ensures that the file we selected in step 3 is copied to the project in this chapter, so that we can avoid the accidental change of "cattle. H and cattle. "M" has an impact on the procedures that have taken effect in chapter 1, although we do not change these two codes in this chapter.

Step 5: move the mouse over "Source" in the project browser, select "add" in the pop-up menu, and select "new files" in the sub-menu ", select "cocoa touch classes" on the left side of the create file dialog box, select "nsobject subclass" in the right window, and select "Next ", in the "new file" dialog box, enter "bull" in the "file name" column. m ". Here I did not give a legend. Here, the steps for creating a file are the same as those in step 2 to step 4 of Chapter 2, except that the file name is different. For the first time I saw this article, refer to Chapter 3rd.

Step 6: Open bull. h and make the following changes and save the changes.

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

@ Interface BULL: cattle {
Nsstring*Skincolor;
}
-(Void) Saysomething;
-(Nsstring*) Getskincolor;
-(Void) Setskincolor :( nsstring*) Color;
@ End

 

Step 7: Open bull. M and make the following changes and save

# Import " Bull. h "

@ Implementation Bull
- ( Void ) Saysomething
{
Nslog ( @" Hello, I am a % @ bull, I have % d legs. " , [Self getskincolor], legscount );
}
- (Nsstring * ) Getskincolor
{
Return Skincolor;
}
- ( Void ) Setskincolor :( nsstring * ) Color
{
Skincolor = Color;
}
@ End

 

Step 8: Open the 04-Hello inheritance. M file, make the following changes, and save

# Import < Foundation / Foundation. h >
# Import " Cattle. h "
# Import " Bull. h "

IntMain (IntArgc,Const Char *Argv []) {
NSAID utoreleasepool*Pool=[[NSAID utoreleasepool alloc] init];

Id cattle= [Cattle New ];
[Cattle setlegscount: 4 ];
[Cattle saysomething];

Id redbull = [Bull New ];
[Redbull setlegscount: 4 ];
[Redbull setskincolor: @" Red " ];
[Redbull saysomething];

Bull * Blackbull = [Bull New ];
[Blackbull setlegscount: 4 ];
[Blackbull setskincolor: @" Black " ];
[Blackbull saysomething];

[Pool drain];
Return   0 ;
}

 

Step 9: Select "run" in the menu at the top of the screen, and then select "console". After the console dialog box is opened, select "Build and go" in the upper center of the dialog box ", if nothing happens, the result shown in Figure 4-1 appears. If any unexpected error occurs, check your code carefully. If you find that the Code cannot be executed after careful check, you can download the code prepared by the author for the students. If the author's code still cannot be executed, please let me know.

4.3, subclass and superclass

Let's first recall the cattle. h In chapter 3rd. In cattle. H, we have the following code snippet:

@ Interface cattle: nsobject {

This code tells the compiler that our cattle is an inherited nsobject. In this Code, nsobject is a superclass and cattle is a subclass. In this way, we once obtained a free nsobject method called New.

Id cattle = [Cattle New ];

In the object-oriented programming, if the child class inherits the superclass, some code that has taken effect of the superclass will still be valid in the Child class, this greatly improves the code efficiency. Based on the superclass, we can place some of the functions we need to append to the subclass. In this chapter, we decided to regenerate a subclass bull Based on the cattle class:

1 # Import < Foundation / Foundation. h >
2 # Import " Cattle. h "
3
4 @ Interface BULL: cattle {
5 Nsstring * Skincolor;
6 }
7 - ( Void ) Saysomething;
8 - (Nsstring * ) Getskincolor;
9 - ( Void ) Setskincolor :( nsstring * ) Color;
10 @ End

The first line in the code above is the notification compiler. The declaration part of this class needs a cattle. h file. We are already familiar with this file, which we have constructed in Chapter 3rd. In this chapter, we will not change anything in it.

The second line is to inform the compiler that we need to declare a class named Bull, which is inherited from cattle.

Row 3 adds an instance variable.SkincolorTo save the bull color.

Row 3: we reload the existing data in the cattle class.(Void) SaysomethingInstance method. Heavy Load(Void) SaysomethingThe main reason for this method is that we think what bull says should be different from that of cattle.

From rows 8th to 9th, we declare two new methods for the bull class.(Nsstring*) GetskincolorAnd(Void) Setskincolor :( nsstring*) ColorTo set and read data respectively.Our instance variable skincolor.

Okay. Let's summarize the subclass format during inheritance.

@ Interface Class Name: parent class name {
Object variable type object variable name;

}
- (Return Value Type) Name of the overloaded method;
+ (Return Value Type) Name of the overloaded method;
- (Return Value Type) other method names: (variable type) variable name;

@ End

4.4, self and super

Let's start "bull. m ".SaysomethingAs shown in the following code:

Nslog ( @" Hello, I am a % @ bull, I have % d legs. " , [Self getskincolor], legscount );

In this sentence, we found that the first new friend is % @, which is telling the compiler to replace % @ with a string defined later, the string we provide to the compiler here is[Self getskincolor]. Here, the students will find a new friend self.

In the method definition field of the class, we sometimes need to access the instance variables or methods of the class. After the class is instantiated, we can use a pointer pointing to the class itself. In Java or C ++, the name is this. In objective-C, the name is self. Self itself is a pointer variable of the ID type. We have explained in chapter 3rd that the method calling format is as follows:

[Object or class name Method Name: parameter sequence];

In the class method definition field, when we need to call other methods of the class, we need to specify the object or Class Name, our method is an instance method, so we need an object pointing to ourselves. here we need to use self.

Let's assume that, if there is a parameter name in the parameter sequence in the method declaration and the instance variables of the class are repeated, and for some reason we cannot change the name of the parameter and object variable, what should we do? The answer is to use self in the following format:

Self -> Variable name

In this way, we can obtain the value of the class variable. Of course, if there is no name conflict, we can omit self->. xcode is smart enough to identify our instance variables, and change the instance variables in our code to the corresponding conspicuous color.

If we need to access the superclass method or variable in the class method (of course, the access is a visible method or variable for the subclass), how should we write it? The answer is that super and super are essentially ID pointers. Therefore, the writing format when super is used to access variables and methods is exactly the same as self.

The other code in "bull. m" does not have anything new, so I will not repeat it here.

4.5. Execution of superclass and subclass Methods

Let's take a look at the code snippet below 04-Hello inheritance. M.

1 Id redbull = [Bull New ];
2 [Redbull setlegscount: 4 ];
3 [Redbull setskincolor: @" Red " ];
4 [Redbull saysomething];
5
6 Bull * Blackbull = [Bull New ];
7 [Blackbull setlegscount: 4 ];
8 [Blackbull setskincolor: @" Black " ];
9 [Blackbull saysomething];

 

The 1st-line code is explained in chapter 3rd. Let's take a look at the 2nd-line code.

The Code in line 2 is actually directedRedbull sendsSetlegscountMessage. The parameter is 4. We didn't define it in bull.SetlegscountMethod, but from the output of the console,SetlegscountIt is obviously executed. During executionRedbullSendSetlegscountWhen the message is sent, the runtime will be inSearch in the ing tableSetlegscount. runtime cannot be found because it is not defined. If the specified method is not found in the runtime, the super class of bull is required, that is, cattle. Fortunately, runtime found it in cattle.SetlegscountSo it is executed. Since runtime has found the target method and executed it, it stops searching. If Runtime is not found in cattle, it will be searched in cattle's superclass nsobject. If it still cannot be found, it will report an error because nsobject is the root class. We will explain the specific internal mechanism in the following sections.

The second line of code is to set skincolor.

The Code in line 3 is sent to redbull.Saysomething. According to the runtime search logic of Row 3, it first looksSaysomethingThis Runtime is very lucky. It is found once, so it is executed immediately. At the same time, the runtime also stops searching. Therefore,SaysomethingWill not be executed.

In row 6th, we defined a blackbull, but this time we didn't use ID as the blackbull type. We usedBull*. In essence, the ID orBull*There is no difference. However, we can imagine that when our program has many ID-type variables, it may be difficult to distinguish what type of variables are. Therefore, without special reasons, we 'd better explicitly write the class name so that others can read it easily. Because bull inherits from cattle, we can also change the code of Line 6

Cattle * Blackbull = [Bull New ];

 

4.6. Summary in this Chapter

Thank you for reading this article! We have learned in this chapter:

    1. The concept of superclass and subclasses and how to define and declare them.
    2. Self and super usage and timing.
    3. Superclass and subclass method execution.

In the next chapter, we will introduce some other important concepts of selector.

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.