컴퓨터

RubyCocoa 간단한 윈도우 띄우기

실마리 2008. 3. 6. 16:56

RubyCocoa는 ruby의 문법을 사용하면서 cocoa 어플리케이션을 만들어볼 수 있어서 매력적입니다. 보통 Xcode와 Interface Builder를 사용하여 NIB파일을 만들고 사용합니다만 다음과 같은 코드로 간단히 기본적인 윈도우를 만들어 볼 수 있습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
require 'osx/cocoa'
include OSX

if $0 == __FILE__ then
  app = NSApplication.sharedApplication()

  frame = [200.0, 300.0, 250.0, 100.0]
  win = NSWindow.alloc.initWithContentRect_styleMask_backing_defer(frame, 15, 2, 0)
  win.setTitle 'HelloWorld'
  win.setLevel(3)      # floating window

  NSNotificationCenter.defaultCenter.addObserver_selector_name_object(app, 'terminate:', NSWindowWillCloseNotification, nil)

  win.display()
  win.orderFrontRegardless()    ## but this one does

  app.run()    
end

Leopard내의 RubyCocoa Example 디렉토리의 HelloWorld.rb 프로그램의 간략버전입니다. 원 버전에서는 Notification을 사용하지 않고 버튼을 눌렀을때 app의 stop이 호출되도록 되어있습니다.

윈도우를 만들어 띄우는것 까지는 비교적 간단한데 끝내는 버튼을 눌렀을때 프로그램이 끝나도록 하는 방법을 찾느라 고생했습니다. 인자를 잘 못 주면 segmentation fault가 나는데 요리조리 바꾸어 조합하면서 시험해보니 NSApplication 객체에 terminate 함수가 바로 호출되도록 하는 것이 제대로 동작하는듯 합니다. Notification의 사용에 대해서는 좀 더 알아봐야 되겠습니다.