MacRuby自定义初始化程序 [英] MacRuby custom initializers

查看:113
本文介绍了MacRuby自定义初始化程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天下午刚发现MacRuby;男人是那曾经的酷!但是,在尝试使用MacRuby-fu扩展旧项目时遇到了一些困难.这是交易:

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:

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

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

因此,在一个红宝石文件中,我们将其命名为Mung.rb,如下所示:

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

当我去实例化Mung时(myObj = Mung.alloc.initWithSomethingElse("Boo"和EvenMore:"US"),运行时会爆炸,告诉我Mung的超级名称'initWithSomethingElse'中没有定义任何方法.是的,但是这意味着我无法在ruby文件中定义自定义初始化程序,我目前的解决方法是提供一个接受哈希值的同质初始化程序,然后各个子类根据需要解析哈希值. :A.关于为什么在super上曾经调用过'initWithSomethingElse'的解释; B.如果无法应用直接解决方案,则可以采用另一种解决方法.谢谢大家!

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!

推荐答案

您无法调用与MacRuby中的方法不同的方法的超级版本. super关键字遵循Ruby语义,并且只会将调用分派到当前方法的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.

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

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.

这篇关于MacRuby自定义初始化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆