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.rb) 时, alloc.initWithSomethingElse("Boo", andEvenMore:"US"),运行时爆炸告诉我 Mung 的 super 中没有定义名为 'initWithSomethingElse' 的方法。这是真的,但这意味着我无法在 ruby 文件中定义自定义初始化程序。我当前的解决方法是提供一个采用哈希值的同质初始化程序,然后各个子类根据需要解析哈希值,我不喜欢这种方法,并且希望:A.解释为什么在 super 上调用“initWithSomethingElse”。和 B. 如果无法应用直接解决方案,请使用替代解决方法,谢谢大家!
Just discovered MacRuby this afternoon; man is that ever COOL! However, I've run into some difficulties while attempting to extend an old project with some MacRuby-fu. Here's the deal:
So I have a superclass in Objective-C that looks like this:
@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
So, in a ruby file, we'll call it Mung.rb that looks like this:
class Mung < Foo
def initWithSomethingElse(else, andEvenMore:more)
super.initWithName("Moop", andLocation:else, andSomethingElse:more.addVal(42))
self
end
end
When I go to instantiate a Mung (myObj = Mung.alloc.initWithSomethingElse("Boo", andEvenMore:"US"), the runtime explodes telling me there is no method defined in Mung's super called 'initWithSomethingElse'. This is true, but it means that I cannot define custom initializers in ruby files. My current workaround is to provide a homogenous initializer that takes a hash, and then the individual subclasses parse the hash as needed. I don't like this approach and would like: A. An explanation of why 'initWithSomethingElse' is ever called on super, and B. If no direct solution can be applied, an alternative workaround. Thanks guys!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您无法从 MacRuby 中的方法调用不同方法的超级版本。 super 关键字遵循 Ruby 语义,并且只会分派对当前方法的超级版本的调用。
在您的情况下,您可能希望直接将 initWithName:andLocation:andSomethingElse: 发送给 self,如果需要,您可以在类上重新定义此选择器并适当地调用 super 。
You can't call the super version of a different method from a method in MacRuby. The super keyword respects the Ruby semantics and will only dispatch a call to the super version of the current method.
In your case, you may want to send initWithName:andLocation:andSomethingElse: to self directly, and if needed, you can re-define this selector on the class and call super appropriately.