开发者

MacRuby custom initializers

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 fi开发者_开发问答le, 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!


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜