使用RubyMotion中的控制器管理NSWindows

时间:2014-02-01 14:39:34

标签: rubymotion

如何从控制器中继续引用NSWindow?关闭窗口将导致它被解除分配,并使控制器的变量指向坏内存。

基本上,这是行为的规范:

describe "Opening and closing NSWindow" do

  before do
    @app = NSApplication.sharedApplication
    @controller = MyWindowController.new
  end

  it "opens and closes the window" do
    @controller.open
    @app.windows.length.should == 1
    @controller.close
    @app.windows.length.should == 0
  end

  it "can reopen a new window" do
    @controller.open
    @controller.close
    @controller.open # Crashes 
    @app.windows.length.should == 1
  end

  it "doesn't care how many times new windows are reopened" do
    100.times do
      @controller.open
      @controller.close
    end
    @app.windows.length.should == 0
  end

  it "releases windows when closed" do
    @controller.open
    @controller.close
    @controller.window.should == nil
  end
end

崩溃实施:

class MyWindowController
  def open
    @window = NSWindow.alloc.initWithContentRect(
          NSMakeRect(200, 200, 200, 200),
          styleMask: NSTexturedBackgroundWindowMask,
          backing: NSBackingStoreBuffered,
          defer: false
          )
    @window.orderFrontRegardless
  end

  def close
    @window.close
  end

  def window
    @window
  end
end

1 个答案:

答案 0 :(得分:0)

class MyWindowController < UIViewController

  def viewDidLoad
    super.tap do
      self.view.addSubview(myWindow)
    end
  end

  def myWindow
    @myWindow ||= NSWindow.alloc.initWithContentRect(
              NSMakeRect(200, 200, 200, 200),
              styleMask: NSTexturedBackgroundWindowMask,
              backing: NSBackingStoreBuffered,
              defer: false
              ).tap do |window|
      window.orderFrontRegardless
    end
  end

  def close
    myWindow.close
  end

end