gpt4 book ai didi

objective-c - Objective-C 中的指定初始化器

转载 作者:搜寻专家 更新时间:2023-10-30 19:53:27 25 4
gpt4 key购买 nike

只是为了确认在 Objective-C 中创建指定初始化程序的正确方法吗?

这是初始化 ivar 的正确方法吗?

你能建议我改进什么吗?

人.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

人.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];
}

提前致谢!

最佳答案

我认为是正确的。您可以通过从任何其他方法调用 main init 方法来提高效率,这样您就不会进行链式调用,但我认为没有太大区别。

关于objective-c - Objective-C 中的指定初始化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9374400/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com