MacRuby自定义初始化程序

刚刚今天下午发现了MacRuby; 男人是那么酷! 但是,我试图用一些MacRuby-fu扩展旧项目时遇到了一些困难。 这是交易:

所以我在Objective-C中有一个超类,如下所示:

@implementation Foo - (id) init { if (self = [super init]) { //Do nothing, don't have enough data... } return self; } - (id) initWithName:(NSString*)n andLocation:(NSString*)loc andSomethingElse:(Bar*)b { if (self = [super init]) { //Set a LOT of internal state... } return self; } @end 

因此,在ruby文件中,我们将其称为Mung.rb,如下所示:

 class Mung < Foo def initWithSomethingElse(else, andEvenMore:more) super.initWithName("Moop", andLocation:else, andSomethingElse:more.addVal(42)) self end end 

当我去实例化一个Mung(myObj = Mung.alloc.initWithSomethingElse(“Boo”,andEvenMore:“US”)时,运行时爆炸告诉我Mung的超级中没有定义的方法叫做’initWithSomethingElse’。这是真的,但是这意味着我无法在ruby文件中定义自定义初始化器。我目前的解决方法是提供一个带有哈希的同源初始化器,然后各个子类根据需要解析哈希。我不喜欢这种方法,并希望:A。解释为什么’initWithSomethingElse’被称为超级和B.如果没有直接的解决方案可以应用,另一种解决方法。谢谢大家!

您无法从MacRuby中的方法调用不同方法的超级版本。 super关键字尊重Ruby语义,只会调用当前方法的超级版本。

在您的情况下,您可能希望直接将initWithName:andLocation:andSomethingElse:发送给self,如果需要,您可以在类上重新定义此选择器并适当调用super。