Rubymotion:如何从mouseDown(event)块中访问实例变量?

时间:2013-12-19 15:58:44

标签: scope rubymotion mousedown

如何在鼠标事件块中访问实例变量?
即使我从鼠标事件定义中调用其他方法,它也不起作用。

我现在找到的唯一方法是将变量声明为类变量,但我认为这不是正确的方法。

使用新代码更新

app_delegate.rb

class AppDelegate
  def applicationDidFinishLaunching(notification)

    @view = ViewController.new

  end
end

view_controller.rb

class ViewController < NSView

  def init
    @var = "method called from event"
    loadWindow
  end

  def loadWindow
    @window = NSWindow.alloc.initWithContentRect([[400, 500], [480, 200]],
      styleMask: NSTitledWindowMask|NSClosableWindowMask,
      backing: NSBackingStoreBuffered,
      defer: false)
    @window.setTitle("Test")

    @cView = ViewController.alloc.initWithFrame([[400,500], [480, 200]])
    @window.setContentView(@cView)
    @window.orderFrontRegardless
    @window.makeKeyWindow
    runEvent                      # <- This puts "method called from event"
  end

  def runEvent
    puts @var
  end


  def mouseDown event
    runEvent                      # <- This puts a blank line
    puts "mouse click"
  end
end

2 个答案:

答案 0 :(得分:1)

这只是一个假设,因为您没有提供完整的代码段。

如果你有这样的代码:

class SomeController
  @var = "variable"
end

您不是在类级别创建实例变量,而是创建变量。

这将创建一个实例变量:

class SomeClass
  def initialize
    @var = "some value"
  end
end

答案 1 :(得分:0)

您正在创建两个ViewController个实例,一个包含new个实例,另一个包含alloc.initWithFrame()个实例。

new是一种直接映射到alloc.init的类方法,因此@view实例正在调用.init,但.alloc.initWithFrame()不是。{/ p >

输出runEvent内容的是@view实例(创建时),输出空行的实例是@cView的实例({{1 }})。

您需要在常用方法中设置变量,然后提供mouseDown方法:

initWithFrame

使用:

def initWithFrame(frame)
  super
  setVar
  self
end

def init
  super
  setVar
  loadWindow
  self
end

def setVar
  @var = "method called from event"
end

两个旁白:始终在您覆盖的init方法中调用method called from event (main)> method called from event mouse click (main)> method called from event mouse click ,并始终返回super。此外,您加载这些self类的方式有点奇怪;看起来您可以将代码的一半移到ViewController中,并完全避免这种歧义。

相关问题