objective-c - 具有多个参数的类工厂方法

标签 objective-c cocoa osx-yosemite

我正在练习我的 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/

相关文章:

objective-c - 将 sqlite 数据库保存在缓存目录而不是文档中

objective-c - NSOutlineView拖放问题

ios - 使用 AFNetworking 丢失网络连接问题

iphone:如何停止增量变量

objective-c - 为什么自动完成在 xcode 中新创建的协议(protocol)头文件中不起作用?

iphone - 如何更改导航栏上标签的字体及其大小 - ios8 #swift

python - Meld 在 OSX 10.10 上有错误

cocoa - 使用 Cocoa API 的综合图像处理示例

xcode - 如何反转选定 NSTableView 行的文本颜色

android - 无法在 OSx Yosemite 上连接我的 Nexus5