我正在练习我的 Objective C 技能,并且遇到了一个小问题,尽管我似乎无法在任何地方找到该问题的直接答案。在我正在阅读的 Apple 开发人员指南中,没有任何内容告诉我如何使用具有多个参数(例如 3 个参数)的类工厂方法,并通过重写的 init 方法返回初始化的对象。
这里我有一个简单的类,名为 XYZPerson。
@implementation XYZPerson
// Class Factory Method
+ (id)person:(NSString *)firstName with:(NSString *)lastName andWith:(NSDate *)dateOfBirth {
// need to return [ [self alloc] init with the 3 paramaters]; here
// Or some other way to do so..
}
// Overridden init method
- (id)init:(NSString *)firstName with:(NSString *)lastName andWIth:(NSDate *)dateOfBirth {
self = [super init];
if (self) {
_firstName = firstName;
_lastName = lastName;
_dateOfBirth = dateOfBirth;
}
return self;
}
// Use the initialized instance variables in a greeting
- (void)sayHello {
NSLog(@"Hello %@ %@", self.firstName, self.lastName);
}
然后在我的 main 中我实例化一个 XYZPerson 对象
XYZPerson *person = [XYZPerson person:@"John" with:@"Doe" andWith:[NSDate date]];
[person sayHello];
有人可以给我一个关于如何正确执行此操作的小提示吗?
最佳答案
如果我理解您的问题,您需要以下内容:
+ (id)person:(NSString *)firstName with:(NSString *)lastName andWith:(NSDate *)dateOfBirth {
XYZPerson *result = [[self alloc] init:firstName with:lastName andWith:dateOfBirth];
return result;
}
如果您不使用 ARC,请将 autorelease
添加到 return
。
顺便说一句 - 将 init
方法的返回类型更改为 instancetype
而不是 id
。
关于objective-c - 具有多个参数的类工厂方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27773075/