OC开发之——自定义构造方法(29)

一 概述

  • 通过系统默认的构造方法初始化后的类,变量的值都一样(未初始化为0,初始化后为固定值)
  • 通过自定义构造方法,初始化时设置变量值,这样构造后的类变量的值就不一样

二 init初始化过程

2.1 示意图

2.2 说明

  • 继承关系:NSObject是父类,Person继承NSObject,Student继承Student
  • init初始化时,Stuent的init会调用Person的init,Person的init会调用NSObject的初始化

三 自定义构造方法

3.1 Person类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
//Person.h
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property NSString *name;
@property int age;

-(instancetype)initWithName:(NSString*)name;
-(instancetype)initWithAge:(int)age;
-(instancetype)initWithName:(NSString*)name andAge:(int)age;
@end

//Person.m

#import "Person.h"
@implementation Person
-(instancetype)init
{
if(self=[super init])
{
_name=@"jack";
}
return self;
}
- (instancetype)initWithName:(NSString *)name
{
if(self=[super init])
{
_name=name;
}
return self;
}
- (instancetype)initWithAge:(int)age
{
if(self=[super init])
{
_age=age;
}
return self;
}
- (instancetype)initWithName:(NSString *)name andAge:(int)age
{
if(self=[super init])
{
_name=name;
_age=age;
}
return self;
}
@end

3.2 Student类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
//Student.h
#import "Person.h"
@interface Student : Person
@property int no;
-(instancetype)initWithNo:(int)no;
-(instancetype)initWithName:(NSString*)name andAge:(int)age andNo:(int)no;
@end

//Student.m
#import "Student.h"

@implementation Student

- (instancetype)initWithNo:(int)no
{
if(self=[super init])
{
_no=no;
}
return self;
}
//- (instancetype)initWithName:(NSString *)name andAge :(int)age andNo:(int)no
//{
// if(self=[super init])
// {
// self.name=name;
// self.age=age;
// _no=no;
// }
// return self;
//}
- (instancetype)initWithName:(NSString *)name andAge:(int)age andNo:(int)no
{
if(self=[super initWithName:name andAge:age])
{
_no=no;
}
return self;
}
@end

四 构造方法调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#import <Foundation/Foundation.h>
#import "Person.h"
#import "Student.h"

int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
Person *p=[[Person alloc]init];
//NSLog(@"Person 的名字是%@",p.name);

//使用自定义name
Person *p1=[[Person alloc] initWithName:@"Rose"];
//NSLog(@"Person的名字是%@",p1.name);

Person *p2=[[Person alloc]initWithAge:10];
//NSLog(@"Person的年龄是%d",p2.age);

Person *p3=[[Person alloc]initWithName:@"jack" andAge:10];
//NSLog(@"Person的名字是%@,年龄是%d",p3.name,p3.age);

Student *stu=[[Student alloc]initWithNo:1];
//NSLog(@"Student的编号是%d",stu.no);

Student *stu2=[[Student alloc]initWithName:@"jack" andAge:10 andNo:1];
NSLog(@"Student的名字是%@,年龄是%d,编号是%d",stu2.name,stu2.age,stu2.no);

}
return 0;
}