A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© wdcew 中级黑马   /  2015-8-16 22:18  /  475 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

便利构造器
Car * car  = [[Car alloc] init];alloc是类方法,init是实例方法,Car alloc创建了一个对象,然后调用对象的init方法进行该对象的初始化。
-(id) initWithName : (NSString *) aName
andAge : (int) anAge
{
if(self = [super init]){
name = [aName retain];
age = anAge;
}
}
这里不是判断self与[super init]是否相等,而是判断是否可以成功初始化。而用if判断下,是为了防止self为空的情况
+(id) studentWithName : (NSString *) aName
andAge : (int ) anAge
{
id obj = [[Student alloc] initWithName:aName andAge:anAge];
//设置obj的成员值
[obj autorelease];
return obj;
}
Student *stu1=[Student studentWithName:achao andAge:22];
这个初始化的临时对象不用手动释放,类方法的便利构造器初始化实例变量后不用手动release,然后直接用stu1来调用类的方法来使用被初始化的值

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马