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