RubyCocoa and subclassing OSX classes

If you create a subclass C inside a module M, the result is two distinct classes: M::C (as expected) and OSX::C (an unpleasant surprise):

require osx/cocoa
puts OSX.const_defined?(’Squiggle‘)    # => false

module M
  class Squiggle <  OSX::NSObject

puts OSX.const_defined?(’Squiggle‘)    # => true ?!
puts M.const_get(’Squiggle‘)           # => M::Squiggle
puts OSX.const_get(’Squiggle‘)         # => OSX::Squiggle
puts M::Squiggle == OSX::Squiggle      # => false
puts M::Squiggle.object_id
puts OSX::Squiggle.object_id

RubyCocoa 0.13.1, OSX 10.5.5

I believe this is because Objective-C doesn’t “get” separate namespaces - all classes are in the same namespace, which is why you can’t do this:

irb(main):001:0> module Second; class Quux < OSX::NSObject; end; end
=> nil
irb(main):002:0> module Second; class Quux < OSX::NSObject; end; end
objc/oc_import.rb:266: warning: Cannot create Objective-C class for
Ruby class `Quux', because another class is already registered in
Objective-C with the same name. Using the existing class instead for
the Ruby class representation.
objc[12661]: objc_registerClassPair: class 'Quux' was already registered!

Leave a Reply

You must be logged in to post a comment.