只是要确认是否在Objective-C中创建指定初始值设定项的正确方法?
这是启动ivars的正确方法吗?
你能建议我改进一下吗?
Person.h
@interface Person : NSObject
@property (nonatomic, retain) NSString *name;
@property (nonatomic, assign) int age;
@property (nonatomic, assign) NSString *sex;
@property (nonatomic, assign) int weight;
-(id)initWithName:(NSString *)name;
-(id)initWithName:(NSString *)name age:(int)age;
-(id)initWithName:(NSString *)name age:(int)age sex:(NSString *)s;
-(id)initWithName:(NSString *)name age:(int)age sex:(NSString *)s andWeight:(float)w;
@end
Person.m
@implementation Person
@synthesize name = _name;
@synthesize sex = _sex;
@synthesize age = _age;
@synthesize weight = _weight;
-(id)initWithName:(NSString *)name age:(int)age sex:(NSString *)s andWeight:(float)w
{
if(self = [super init])
{
[self setName:name];
[self setAge:age];
[self setSex:s];
[self setWeight:w];
}
return self;
}
-(id)initWithName:(NSString *)name age:(int)age sex:(NSString *)s
{
return [self initWithName:name age:age sex:s andWeight:0];
}
-(id)initWithName:(NSString *)name age:(int)age
{
return [self initWithName:name age:age sex:0];
}
-(id)initWithName:(NSString *)name
{
return [self initWithName:name age:0];
}
-(id)init
{
return [self initWithName:nil];
}
提前致谢!
答案 0 :(得分:6)
我认为这是正确的。您可以通过从任何其他方法调用主init方法来提高效率,因此您不会链接调用,但我认为没有太大的区别。
答案 1 :(得分:3)
是的,这是一种典型的模式。指定的初始化程序具有所有参数,较简单的初始化程序填充默认值。
答案 2 :(得分:2)
我建议直接从每个方法调用-(id)initWithName:(NSString *)name age:(int)age sex:(NSString *)s andWeight:(float)w
。它可以避免多次执行。
Apple recommends against使用init
或dealloc
中的访问者方法。你有_name
之类的变量,你可以使用它。