MacRuby custom initializers

空扰寡人 提交于 2020-01-06 15:31:50

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/4352575/macruby-custom-initializers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!