便利初始化函数和便利构造器
mian.m
#import <Foundation/Foundation.h>
#import "Teacher.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Teacher *teacher = [[Teacher alloc]init];
[teacher sayWord];
Teacher *teacher1 = [[Teacher alloc]init];
[teacher1 sayWord];
Teacher *teacher2 = [[Teacher alloc]initWithName:@"zengxinsheng" andAge:18];
[teacher2 sayWord];
Teacher *teacher3 = [Teacher teacherWithName:@"xuyu" andAge:18];
[teacher3 sayWord];
}
return 0;
}
Teacher.h
#import <Foundation/Foundation.h>
@interface Teacher : NSObject
{
NSString *_name ;
NSInteger _age ;
}
-(void)sayWord ;
//便利初始化函数
//注意命名规范: init开头
-(id)initWithName:(NSString *)name
andAge:(NSInteger)age;
/*
便利构造器(类方法)
便利构造器只不过是把对象分配内存 和 便利初始化函数 初始化对象的代码封装起来,让用户使用起来更加方便
注意命名规范:className 开头,例如teacher
*/
+(id)teacherWithName:(NSString *)name
andAge:(NSInteger)age ;
Teacher.m
#import "Teacher.h"
@implementation Teacher
/*
id:返回的类型是id数据类型,它是动态数据类型,它可以指向任何的对象,而不关心具体类型,在运行时检查其具体类型,可以对其发送任何(存在的)消息
self :指向当前对象的指针
super :指向父类对象的指针,子类使用super发送消息时,实际上就是告诉子类调用父类的方法。如果父类没有定义该方法,则会继续在继承链上寻找,直到寻找到位置,如果找NSObject位置依然没有找到,就会报错
其中(self = [super init]),此处[super init]任然返回子类对象,此处的目的是为了初始化父类的实例变量,如果返回nil,表明父类没有alloc成功,即不能再alloc子类对象
*/
-(id)init
{
if (self = [super init])
{
_name = @"Rick";
_age = 25;
}
return self;
}
-(id)initWithName:(NSString *)name andAge:(NSInteger)age
{
if (self = [super init])
{
_name = name;
_age = age;
}
return self;
}
//便利构造器
+(id)teacherWithName:(NSString *)name andAge:(NSInteger)age
{
Teacher *teacher = [[Teacher alloc]initWithName:name andAge:age];
return teacher;
}
-(void)sayWord
{
NSLog(@"Teacher who names %@,%ld years old, say hello guys",_name,_age);
}
@end