from : http://www.cnblogs.com/wendingding/p/3706883.html
自定义构造方法的规范
(1)一定是对象方法,以减号开头。
(2)返回值一般是 instancetype 类型。
(3)方法名一般以 initWith 开头。
代码实现
//// Person.h// WDDGouzaofangfaTest//// Created by LiuChanghong on 15/9/25.// Copyright © 2015年 LiuChanghong. All rights reserved.//#import@interface Person : NSObject@property int age;@property (nonatomic,strong)NSString *name;//接收一个参数age的构造方法-(instancetype)initWithAge:(int)age;//接收两个参数age和name的构造方法-(instancetype)initWithAge:(int)age andName:(NSString *)name;@end
//// Person.m// WDDGouzaofangfaTest//// Created by LiuChanghong on 15/9/25.// Copyright © 2015年 LiuChanghong. All rights reserved.//#import "Person.h"@implementation Person-(instancetype)initWithAge:(int)age{ self = [super init]; if (self) { _age = age; } return self;}-(instancetype)initWithAge:(int)age andName:(NSString *)name{ self = [super init]; if (self) { _age = age; _name = name; } return self;}@end
//// Student.h// WDDGouzaofangfaTest//// Created by LiuChanghong on 15/9/25.// Copyright © 2015年 LiuChanghong. All rights reserved.//#import "Person.h"@interface Student : Person@property int number;//接收三个参数的构造方法-(instancetype)initWithAge:(int)age andName:(NSString *)name andNumber:(int)number;@end
//// Student.m// WDDGouzaofangfaTest//// Created by LiuChanghong on 15/9/25.// Copyright © 2015年 LiuChanghong. All rights reserved.//#import "Student.h"@implementation Student//由于Student类继承自Person类,因此可以直接调用父类Person的构造方法初始化其中两个变量。-(instancetype)initWithAge:(int)age andName:(NSString *)name andNumber:(int)number{ //直接调用父类Person的构造方法初始化其中两个变量。 self = [super initWithAge:age andName:name]; if (self) { _number = number; } return self;}@end
测试主程序
//// main.m// WDDGouzaofangfaTest//// Created by LiuChanghong on 15/9/25.// Copyright © 2015年 LiuChanghong. All rights reserved.//#import#import "Student.h"int main(int argc, const char * argv[]) { @autoreleasepool { Student *student = [[Student alloc]initWithAge:12 andName:@"Mike" andNumber:10086]; NSLog(@"学生的年龄为%d岁,学号为%d,名字为%@",student.age,student.number,student.name); } return 0;}
输出结果
自定义构造方法的使用注意
(1)自己做自己的事情
(2)父类的方法交给父类的方法来处理,子类的方法处理子类自己独有的属性