gpt4 book ai didi

objective-c - 类工厂方法实现

转载 作者:行者123 更新时间:2023-12-04 02:33:25 27 4
gpt4 key购买 nike

所以我正在研究 Apple 的 objective-C 文档(在进入 iphone 开发之前)。其中一个练习指出我应该创建一个指定的初始化程序(带有 3 个参数)和合适的工厂方法。

现在我根据我的理解做了这个但是我无法实现工厂方法,因为我不知道我是否应该在它的实现中使用 alloc 和 init?

练习:

Declare and implement a new designated initializer used to create an XYZPerson using a specified first name, last name and date of birth, along with a suitable class factory method. Don’t forget to override init to call the designated initializer.

代码:

//.h 

-(id)initWithNameAndDob:(NSString *)fName last:(NSString *)lName birth:(NSDate *) dob;

//.m
-(id)initWithNameAndDob:(NSString *)fName last:(NSString *)lName birth:(NSDate *)dob{
self = [super init];
return [self initWithNameAndDob:fName last:lName birth:dob];
}

实现中缺少什么?

谢谢你,

最佳答案

Declare and implement a new designated initializer used to create an XYZPerson using a specified first name, last name and date of birth...

你的声明是正确的,但你的实现是递归的,因为它在调用自己。做类似的事情

//.h
-(id)initWithNameAndDob:(NSString *)fName last:(NSString *)lName birth:(NSDate *) dob;
//.m
-(id)initWithNameAndDob:(NSString *)fName last:(NSString *)lName birth:(NSDate *)dob{
if(self = [super init]) {
// use the parameters to do something, eg.
_fName = fName; // assuming you have an ivar called _fName
_lName = lName; // assuming you have an ivar called _lName
_dob = dob; // assuming you have an ivar called _dob
}
return self;
}

然后

...along with a suitable class factory method.

工厂方法是一种产生对象实例的类方法。最常见的实现是让它分配和初始化对象的新实例并返回它。

//.h
+(instancetype)personWithNameAndDob:(NSString *)fName last:(NSString *)lName birth:(NSDate *) dob {


//.m
+(instancetype)personWithNameAndDob:(NSString *)fName last:(NSString *)lName birth:(NSDate *) dob {
return [[XYZPerson alloc] initWithNameAndDob:fName last:lName birth:dob];
}

最后

Don’t forget to override init to call the designated initializer.

由于您设计的初始值设定项是 initWithNameAndDob:last:birth: 您的 init 实现必须调用它。设计的初始化器的参数必须是合理的默认值,在这种情况下 nil 就可以了。

-(id)init {
return [self initWithNameAndDob:nil last:nil birth:nil];
}

作为最后的评论,我想指出您对初始化程序的命名约定不太好。一个更合适和可读的是

-(id)initWithFirstName:(NSString *)fName lastName:(NSString *)lName dateOfBirth:(NSDate *) dob;

关于objective-c - 类工厂方法实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14092222/

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