Custom constructor and description

Source: Internet
Author: User

Custom constructor and description

  •  

Note: This Objective-C topic is a prelude to iOS development. It also helps 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 or iOS development, ignore this.

Knowledge Review

In lecture 5th, we have introduced how to define classes and create and initialize objects, such as Student class.

1. Student. h
1 #import 
 
  2 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 alloc method to allocate memory in Row 3, and then call the init method to initialize the object.

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

I. Custom Constructor

The default constructor, that is, the init method, does not receive any parameters. Therefore, in actual development, custom constructor is often used for convenience.

Next, you can customize a constructor and input an age parameter to initialize the Student object.

1. Add a method declaration in Student. h.
- (id)initWithAge:(int)age;

* The Method Name of the constructor usually starts with init. the return value is of the id type like the init method. id can represent any OC object.

* This constructor receives an age parameter of the int type to set the value of the member Variable _ age 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 }

* Like Java, the constructor must first call the constructor of the parent class and call the init method of the parent class in line 3. It will return the initialized Student object, here, the return value is assigned to self, and self represents the Student object itself.

* 3rd ~ If self is not nil, that is, the initialization is successful, assign a value to the member Variable _ age.

* The initialization self is returned, and the entire constructor is finished.

3. Simplified Construction Method

Because of the syntax features of C language and OC, we can simplify the constructor by first simplifying 3rd lines.

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) is equivalent

* Merge rows 2nd and 3 to simplify the process.

1 - (id)initWithAge:(int)age {2     if ( self = [super init] ) {3         _age = age;4     }5     return self;6 }

* The general meaning of row 2nd is: first call the constructor init of the parent class, then assign the returned value to self, and then judge whether self is nil.

* Later constructor methods are written as follows:

4. Call the constructor
1 Student *stu = [[Student alloc] initWithAge:10];2 3 NSLog(@"age is %i", stu.age);4 5 [stu release];

* The constructor initWithAge: is called in row 1st, and 10 is passed as the parameter. Therefore, the member Variable _ age of the Student object will change to 10.

* Print the member Variable _ age of Student in Row 3. The result is as follows:

21:36:47. 880 constructor [448: 303] age is 10
Ii. description method 1. NSLog Review

As we all know, we can use the NSLog function to output strings and some basic data classes.

1 int age = 11;2 NSLog(@"age is %i", age);

* % I in row 2nd indicates that an integer data is output, and the variable age on the right replaces the position of % I.

* Output result:

21:43:47. 674 constructor [483: 303] age is 11
2. NSLog output OC object

In addition to the basic data types, the NSLog function can also output any OC objects.

1 Student *stu = [[Student alloc] initWithAge:10];2 3 NSLog(@"%@", stu);4 5 [stu release];

* Use the NSLog function to output the stu object in Row 3. Pay attention to the format character % @ on the left. To output the OC object in the future, use the format character % @.

* Once the NSLog function discovers that an OC object is output with % @, the description method of this object is called (the return value of this method is NSString type, which is a string type in OC ), in addition, replace the string returned by the description method with the position of % @ for output.

* By default, the description method returns the following format: <Class Name: Memory Address of the Object>. Therefore, the output result of the above Code is:

21:46:49. 896 constructor [492: 303]

Student is the class name, 0x100109910 is the object's memory address

* Note: % @ can only be used to output OC objects, and cannot output struct or other types.

* People with Java development experience should be able to 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 way, the meaning of outputting the OC object using NSLog is not very great, because we do not care about the memory address of the object, we are concerned with some variable values in the object. Therefore, the description method is often rewritten to overwrite the default Implementation of the description method.

For example, override the description method of Student and return the value of the member Variable _ age.

1 - (NSString *)description {2     return [NSString stringWithFormat:@"age=%i", _age];3 }

* In row 2nd, the static method stringWithFormat of the NSString class is called to initialize a String object and return this string.

* If you use NSLog, you should be able to understand the meaning of the method parameters in line 1.

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

* Some may find it strange that the previously created Student object needs to be released. Why is the string object created here not released? To thoroughly understand this problem, we need to first understand the memory management of OC. We will not discuss it in detail here. We will discuss memory management in detail in later sections. Remember a rule: Normally, objects returned by static methods do not need to be manually released.

* After rewriting the description method, run the following code again:

1 Student *stu = [[Student alloc] initWithAge:10];2 3 NSLog(@"%@", stu);4 5 [stu release];

Output result:

22:09:56. 625 constructor [531: 303] age = 10
4. description method traps

Do not use both % @ and self in the description method. The following statements are incorrect:

1 - (NSString *)description {2     return [NSString stringWithFormat:@"%@", self];3 }

Row 2nd uses both % @ and self, which indicates that the description method of self is to be called. Therefore, the program will be stuck in an endless loop and the description method will be called cyclically.

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.