"Objective-c" 07-Custom construction methods and Description methods

Source: Internet
Author: User
Knowledge review
First, the custom construction method
Second, the description method
Note: This Objective-C project is a prelude to learning iOS development. It is also designed to allow programmers with experience in object-oriented language development to quickly get started with Objective-C. If you have no programming experience or are not interested in Objective-C and iOS development, please ignore it. Before studying this topic, it is recommended to study the C language topic first.

Back to top Knowledge Review
In Lesson 5, we have introduced how to define classes and create and initialize objects, such as the Student class.

1.Student.h
1 #import <Foundation / Foundation.h>

3 @interface Student: NSObject {
4 int _age;
5}
6-(void) setAge: (int) age;
7-(int) age;
8 @end
 

2.Student.m
 1 #import "Student.h"
 2 
 3 @implementation Student
 4-(void) setAge: (int) age {
 5 _age = age;
 6}
 7-(int) age {
 8 return _age;
 9 }
10 @end
 

3. Create a Student object in the main function
 1 #import "Student.h"
 2 
 3 int main (int argc, const char * argv [])
 4 {
 5
 6 @autoreleasepool {
 7 Student * stu = [[Student alloc] init];
 8         
 9 stu.age = 10;
10
11 [stu release];
12}
13 return 0;
14}
* Call the student's alloc method on line 7 to allocate memory, and then call the init method to initialize the object

* Methods used to initialize objects like init can be called "constructors"

 

Back to top I. Custom Constructor
The default constructor, the init method, does not accept any parameters. Therefore, in actual development, for convenience, the construction method is often customized.

Next, customize a constructor method that can pass in an age parameter to initialize the Student object

1.Add method declaration in Student.h
-(id) initWithAge: (int) age;
* The method name of the constructor usually starts with init. The return value is the same as the init method. The id can represent any OC object.

* This constructor receives an age parameter of type int. The purpose is to set the value of the member variable _age by the way when initializing the Student object.

 

2. Implement the constructor in Student.m
1-(id) initWithAge: (int) age {
2 self = [super init];
3 if (self! = Nil) {
4 _age = age;
5}
6 return self;
7}
* As in Java, the constructor of the parent class must first call the constructor of the parent class. The parent class's init method is called on line 2. It returns the initialized Student object. Here, the return value is assigned to self. Self represents Student Object itself

* Lines 3 to 5 mean: if self is not nil, that is, if initialization is successful, the member variable _age is assigned.

* Finally return self after initialization, the entire constructor is over

 

3. Simplified construction method
Due to the syntax characteristics of C and OC, we can simplify the construction method. Simplify line 3 first.

1-(id) initWithAge: (int) age {
2 self = [super init];
3 if (self) {
4 _age = age;
5}
6 return self;
7}
* If (self) and if (self! = Nil) in line 3 are equivalent

* You can also merge lines 2 and 3 to continue simplifying

1-(id) initWithAge: (int) age {
2 if (self = [super init]) {
3 _age = age;
4}
5 return self;
6}
* The overall meaning of line 2 is: first call the constructor of the parent class init, then assign the return value to self, and then determine whether self is nil

* Later construction methods are written like this

 

4. Call the constructor
1 Student * stu = [[Student alloc] initWithAge: 10];

3 NSLog (@ "age is% i", stu.age);
4
5 [stu release];
* In the first line, the constructor initWithAge: is called, and 10 is passed as a parameter, so the member variable _age of the Student object becomes 10

* Print Student member variable _age on line 3, print the result:

2013-04-19 21: 36: 47.880 Construction method [448: 303] age is 10
 

Back to top Second, description method 1. NSLog review
As we all know, we can use NSLog function to output strings and some basic data classes

1 int age = 11;
2 NSLog (@ "age is% i", age);
* The% i in the second line will output an integer data. The variable age on the right will output the position of% i instead.

* Output results:

2013-04-19 21: 43: 47.674 Construction method [483: 303] age is 11
 

2.NSLog output OC object
In fact, in addition to the basic data types, the NSLog function can also output any OC object

1 Student * stu = [[Student alloc] initWithAge: 10];

3 NSLog (@ "% @", stu);
4
5 [stu release];
* In the third line, use the NSLog function to output the stu object. Note the format character% @ on the left. If you want to output the OC object in the future, you must use the% @ format character.

* Once the NSLog function finds that an OC object is output with% @, it will call the description method of this object (the return value of this method is NSString type, which is a string type in OC) and replace the string returned by the description method % @ For output

* The default implementation of the description method returns the format: <class name: memory address of the object>, so the output of the above code is:

2013-04-19 21: 46: 49.896 Construction method [492: 303] <Student: 0x100109910>
Student is the class name, 0x100109910 is the memory address of the object

* Note that% @ can only be used to output OC objects, and cannot output other types such as structures

* People with Java development experience should feel that the description method in OC is the toString method in Java

 

3. Override the description method
The default implementation of the description method is to return the class name and the memory address of the object. In this case, using NSLog to output the OC object is not very significant, because we don't care about the memory address of the object, we are more concerned about some internal variables value. Therefore, the description method will often be overridden to override the default implementation of the description method

For example, override the description method of Student to return the value of the member variable _age

1-(NSString *) description {
2 return [NSString stringWithFormat: @ "age =% i", _age];
3}
* In the second line, the static method stringWithFormat of the NSString class is called to initialize a string object and return the string

* If you use NSLog, you should understand what the method parameters in line 2 mean.

* If _age is 10, the string returned by the description method is @ "age = 10"

* Some people may find it strange that the Student object created earlier needs to be released. Why is the string object created here not to be released? To fully understand this problem, you need to understand OC's memory management first. We won't discuss it in detail here. We will discuss the memory management in detail later. You can remember one rule first: In general, objects returned by static methods do not need to be released manually.

* After rewriting the description method, execute the following code again

1 Student * stu = [[Student alloc] initWithAge: 10];

3 NSLog (@ "% @", stu);
4
5 [stu release];
The output is:

2013-04-19 22: 09: 56.625 Construction method [531: 303] age = 10
 

Trap of 4.description method
Never use% @ and self in the description method at the same time. The following is wrong:

1-(NSString *) description {
2 return [NSString stringWithFormat: @ "% @", self];
3}
Line 2 uses both% @ and self to represent the description method of self. Therefore, the program will end up in an endless loop. The description method will be called in a loop.

[Objective-C] 07-Custom constructor and description method 
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.