本帖最后由 cnchenys 于 2014-4-2 21:40 编辑
类似于Java中的构造方法,
指的是在init的时候,同时给属性变量赋值的方法
比如
@interface Person : NSObject
{
int _age;
NSString *_name;
}
- (Person *)initWithAge: (int)age andWithName: (NSString *)name;
+ (Person *)initWithAge: (int)age andWithName: (NSString *)name;//这个类方法在返回Person对象时,就可以给_age和_name赋值,这个就是便利构造器
@end
@implementation Person
- (Person *)initWithAge: (int)age andWithName: (NSString *)name
{
_age = age;
_name = name;
}
+ (Person *)initWithAge: (int)age andWithName: (NSString *)name
{
return [[Person alloc] initWithAge:age andWithName:name];
}
@end
int main()
{
Person *p = [Person initWithAge: 10 andWithName: @"jason"];// 在init时就赋值了age和name属性
return 0;
}
|