Objective-c Learning-facilitation of initialization functions and convenience constructors

Source: Internet
Author: User

In object-oriented languages, OBJECTIVE-C's handy initialization function can be understood as a constructor with parameters, such as java,c++, but somewhat different ...

For example, use the student class as an example

  

First is the Student.h file

#import <Foundation/Foundation.h>  

@interface Student: nsobject  

Defining Properties

@property nsstring *studentname; // student name

@property int age ; // student age

 constructors with name parameters and age parameters ( facilitates construction of initialization functions )

-(ID) initwithname: (nsstring *) name andwithage: (int) age;

 Convenience Constructors ( is class method )

+ (ID) initwithname: (nsstring *) name andwithage: (int) age;

@end


Then the STUDENT.M file that manages the implementation

#import "Student.h"

@implementation Student

 Constructors with name parameters and age parameters (facilitates construction of initialization functions)

-(ID) Initwithname: (NSString *) name andwithage: (int) Age

{

if (self = [super init])

{

[Self setstudentname:name];

[Self setage:age];

}

return self;

}

  Convenience constructors (is class method)

+ (ID) initwithname: (NSString *) name andwithage: (int) Age

{

Student *student = [[Student alloc] Initwithname:name andwithage:age];

return student ;

}

@end

See Usage in MAIN.M

#import <Foundation/Foundation.h>

#import "Student.h"

int main (int argc, const char * argv[]) {

//Pre-defined method

Student *student = [[Student alloc]initwithname:@ "Xiao Ming" andwithage:19];

        

//With convenient constructors, it can be seen from a convenient constructor that the definition is much simpler

Student *student1 = [Student initwithname:@ "Xiao Ming" andwithage:19];

return 0;

}

Objective-c Learning-facilitation of initialization functions and convenience constructors

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.