您的位置:首页 > 其它

初学者初始化方法 便利构造器

2015-09-09 15:28 375 查看
#pragma mark 初始化方法(在这里,我是初始化方法,通常情况下,把参数最全的初始化方法作为指定初始化方法)

-(id)initWithName:(NSString *)name withAge:(NSString *)age withSex:(NSString *)sex

{

self = [super init]; //父类初始化 子类self继承于父类super

if (self) { //因为父类可能初始化不成功。这时候子类没有必要进行初始化

_name = name;

_sex = sex;

_age = age;

}

return self;

}

#pragma mark 初始化方法2(初始值:name,sex)

-(id)initWithName:(NSString *)name withSex:(NSString *)sex

{

self = [self initWithName:name withAge:nil withSex:sex];

return self;

}

-(id)initWithAge:(NSString *)age withSex:(NSString *)sex

{

self = [self initWithName:nil withAge:age withSex:sex];

return self;

}

-(id)initWithName:(NSString *)name withAge:(NSString *)age

{

self = [self initWithName:name withAge:age withSex:nil];

return self;

}

#pragma mark 初始化方法3

-(id)initWithName:(NSString *)name

{

return [self initWithName:name withAge:nil withSex:nil];

}

#pragma mark setter 方法

-(void)setName:(NSString *)name // 有几个冒号有几个参数 setName:是方法名

{

_name = name;

}

-(void)setSex:(NSString *)sex

{

_sex = sex;

}

-(void)setAge:(NSString *)age

{

_age = age;

}

#pragma mark getter 方法

-(NSString *)getterName

{

return _name;

}

-(NSString *)getterSex

{

return _sex;

}

-(NSString *)getterAge

{

return _age;

}

#pragma mark 便利构造器1

+(id)personWithName:(NSString *)name withAge:(NSString *)age withSex:(NSString *)sex

{

// _name = name;

// _age = age;

// 类方法里面,绝对不可能出现实例变量

Person *p = [[Person alloc]initWithName:name withAge:age withSex:sex];

return p;

}

#pragma mark 便利构造器 2

+(id)personWithName:(NSString *)name

{

return [self personWithName:name withAge:nil withSex:nil];

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: