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

时间:2015-01-05 03:36:44

标签: 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);
}

然后在我的主要部分我实例化一个XYZPerson对象

XYZPerson *person = [XYZPerson person:@"John" with:@"Doe" andWith:[NSDate date]];
[person sayHello];

任何人都可以给我一个关于如何正确执行此操作的小指针吗?

2 个答案:

答案 0 :(得分:1)

如果我理解您的问题,您需要以下内容:

+ (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

BTW - 将init方法的返回类型更改为instancetype而不是id

答案 1 :(得分:0)

@implementation XYZPerson

// Class Factory Method
+ (instanceType ) person:(NSString *)firstName with:(NSString *)lastName andWith:(NSDate *)dateOfBirth {

return [[[self class] alloc]init: firstName with: lastName andWith:dateOfBirth];

}

- (instanceType ) init:(NSString *)firstName with:(NSString *)lastName andWIth:(NSDate *)dateOfBirth {
    self = [super init];

    if (self) {
        _firstName = [firstName copy];
        _lastName = [lastName copy];
        _dateOfBirth = [dateOfBirth copy];
//nb added copy to each of these, we do not own these objects, they could be lost to us..

///  or you could do this instead..
//assuming you synthesised getters/setters for (strong) properties..

[self setFirstName:firstName];
[self setLastName:lastName];
[self setDateOfBirth: dateOfBirth];

    }

    return self;
}