且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

继承工厂方法应该怎么做?

更新时间:2023-12-03 19:47:10

你通常应该使用 [ [[self class] alloc] init ...] 在工厂方法中确保它们创建正确类的实例。请注意, class 不是属性(实际上,没有'class property'这样的东西)所以使用点语法是不合适的。

You should generally use [[[self class] alloc] init...] in factory methods to ensure that they create instances of the correct class. Note that class isn't a property (and in fact, there's no such thing as a 'class property') so the use of dot syntax there is inappropriate.

编辑

正如@ArkadiuszHolko所说(和Rob,谢谢),你现在应该使用 instancetype 而不是 id 作为返回值,以获得强类型的好处,同时保持类型的灵活性子类。顺便说一句,Apple的命名惯例建议避免在方法名称中使用和这个词。因此,请考虑重写您的便捷方法:

And as pointed out by @ArkadiuszHolko (and Rob, thanks), you should now use instancetype rather than id for the return value, to get the benefits of strong typing while maintaining type flexibility for subclasses. And by the way, Apple's naming conventions suggest avoiding using the word 'and' in method names. So consider rewriting your convenience method like so:

+ (instancetype)dateWithMonth:(int)month day:(int)day year:(int)year
{
    return [[self alloc] initWithMonth:month day:day year:year];
}