1、自定义构造方法的规范
(1)一定是对象方法,一定以 - 开头
(2)返回值一般是id类型
(3)方法名一般以initWith开头
以Person类为例,初始化姓名和年龄属性
Person.h代码
1 #import <Foundation/Foundation.h>
2 @interface Person : NSObject
3 @property NSString *name;
4 @property int age;
5 //初始化_name
6 - (id)initWithName: (NSString *)name;
7 //初始化_age
8 - (id)initWithAge: (int)age;
9 //同时初始化_name和_age
10 - (id)initWithName: (NSString *)name andAge: (int)age;
11 @end
注意第6 8 10行代码:符合自定义构造方法的规范: 1>以 - 开头; 2>返回值类型为id类型; 3>方法名以 initWith开头
Person.m代码
1 #import "Person.h" 2 @implementation Person 3 - (id)initWithName: (NSString *)name 4 { 5 if(self = [super init]) 6 { 7 _name = name; 8 } 9 return self; 10 } 11 - (id)initWithAge: (int)age 12 { 13 if(self = [super init]) 14 { 15 _age = age; 16 } 17 return self; 18 } 19 20 - (id)initWithName: (NSString *)name andAge: (int)age 21 { 22 if(self = [super init]) 23 { 24 _name = name; 25 _age = age; 26 } 27 return self; 28 } 29 @end
上述代码分别对3种自定义构造方法进行实现。
牢记格式:
1 - (id)initWithName: (NSString *)name andAge: (int)age
2 {
3 if(self = [super init])
4 {
5 _name = name;
6 _age = age;
7 }
8 return self;
9 }
main.m代码
1 #import <Foundation/Foundation.h>
2 #import "Person.h"
3 int main(int argc, const char * argv[])
4 {
5 Person *person1 = [[Person alloc] initWithName: @"玲玲"];
6 Person *person2 = [[Person alloc] initWithAge:20];
7
8 Person *person3 = [[Person alloc] initWithName:@"宁宁" andAge:24];
9
10 NSLog(@"person1名字:%@", person1.name);
11 NSLog(@"person2年龄:%i", person2.age);
12
13 NSLog(@"person3名字叫:%@, 年龄:%i", person3.name, person3.age);
14 return 0;
15 }
运行,输出结果为:
2、假如在创建一个子类Student
Student.h
1 #import "Person.h" 2 @interface Student : Person 3 @property int no;//学号 4 //同时初始化姓名 年龄 学号 5 - (id)initWithName:(NSString *)name andAge:(int)age andNo:(int)no; 6 @end
Student.m
1 #import "Student.h" 2 @implementation Student 3 - (id)initWithName:(NSString *)name andAge:(int)age andNo:(int)no 4 { 5 //将name age传递到父类方法中进行初始化 6 if(self = [super initWithName:(NSString *)name andAge:(int)age]) 7 { 8 _no = no; 9 } 10 return self; 11 } 12 @end
这里值得注意的是第6行,我们将name age传递给父类方法进行初始化,而不是在子类中初始化。以后要尽量这么写,体会编程思想。
3、总结
(1)牢记规则:
1>一定是对象方法,一定以 - 开头
2>返回值一般是id类型
3>方法名一般以initWith开头
1 //初始化_name 2 - (id)initWithName: (NSString *)name; 3 //初始化_age 4 - (id)initWithAge: (int)age; 5 //同时初始化_name和_age 6 - (id)initWithName: (NSString *)name andAge: (int)age;
(2)构造方法的结构
1 - (id)initWithName: (NSString *)name andAge: (int)age 2 { 3 if(self = [super init]) 4 { 5 _name = name; 6 _age = age; 7 } 8 return self; 9 }
(3)父类中存在的属性,尽量传递给父类方法来初始化。