声明:
-(id)initWithName:(NSString *)name andAge:(int)age andSex:(NSString *)sex andTalent:(NSString *)talent andMate:(id)mate;
+(id)machineWithName:(NSString *)name andAge:(int)age andSex:(NSString *)sex andTalent:(NSString *)talent andMate:(id)mate;
实现:
-(id)initWithName:(NSString *)name andAge:(int)age andSex:(NSString *)sex andTalent:(NSString *)talent andMate:(id)mate
{
self=[super init];
if (self)
{
_name=name;
_age=age;
_sex=sex;
_talent=talent;
_mate=mate;
}
return self;
}
+(id)machineWithName:(NSString *)name andAge:(int)age andSex:(NSString *)sex andTalent:(NSString *)talent andMate:(id)mate
{
Machine *mac=[[Machine alloc]initWithName:name andAge:age andSex:sex andTalent:talent andMate:mate];
return [mac autorelease];//便利构造器内部已经实现内存管理
}
调用:
Machine *mac=[Machine machineWithName:@"machine" andAge:5 andSex:@"?" andTalent:@"HP 10,MP 0,PW 100" andMate:nil];
注意:
便利构造器方法以类名开头
类方法内部不能用实例变量
类方法只能以类(名)来调用 |
|