咱們知道, 在 Cocoa 中提供了兩種字符串類: NSString 和 NSMutableString, 前者用於處理內容不變, 固定的字符串, 好比窗口標題; 後者用於處理內容可變的字符串, 固然後者也能夠用於前者的使用場合.ui
由於後者 NSMutableString 類是在繼承 NSString 類的繼承上建立的, 因此 NSMutableString 具備NSString 中全部的功能.code
在 Objective-C 代碼中一般會使用以下的格式來定義字符串:對象
NSString string = @"This is my string";
語法很是簡單明瞭, 可是有一個問題:使用加 @ 符號的方式只能定義英文數字字符串, 若是想定義中文等多字節字符串, 這種方法是不支持的.繼承
下面給出一種 Objective-C 中定義中文字符串的示例:字符串
NSString* string; string = [NSString stringWithCString:"你好,我是中文字符串!" encoding:NSUTF8StringEncoding];
是否是以爲這段代碼特別繁瑣, 若是轉化爲 Common Lisp 代碼, 也比較麻煩, 不過 Clozure CL 已經提供了一種很是簡單的生成中文字符串的方法, 以下:get
(ccl::%make-nsstring "這是使用中文字符串的簡單方法")
舉個實際的例子, 先繪製一個小窗口, 窗口標題爲英文:string
(in-package "CL-USER") (require "COCOA") (defclass window-view (ns:ns-view) () (:metaclass ns:+ns-object)) (objc:defmethod (#/drawRect: :void) ((self window-view) (rect :<NSR>ect)) (#/set (#/blueColor ns:ns-color)) (#_NSRectFill (#/bounds self))) (defun show-window () (ccl::with-autorelease-pool (let* ((rect (ns:make-ns-rect 0 0 350 350)) (w (make-instance 'ns:ns-window :with-content-rect rect :style-mask (logior #$NSTitledWindowMask #$NSClosableWindowMask #$NSMiniaturizableWindowMask) :backing #$NSBackingStoreBuffered :defer t))) (#/setTitle: w #@"This is a English Title!") (#/setContentView: w (#/autorelease (make-instance 'window-view))) (#/center w) (#/orderFront: w nil) (#/contentView w)))) (show-window)
截圖以下:it
接着咱們修改一下這句:io
(#/setTitle: w #@"This is a English Title!")
把它改成:table
(#/setTitle: w (ccl::%make-nsstring "這是使用中文字符串的簡單方法"))
固然了, 咱們能夠直接運行上述兩段生成英文字符串和中文字符串的代碼, 比較一下它們返回的結果,以下:
? #@"This is a English Title!" #<NS-CONSTANT-STRING "This is a English Title!" (#x65BBD0)> ? (ccl::%make-nsstring "這是使用中文字符串的簡單方法") #<NS-MUTABLE-STRING "這是使用中文字符串的簡單方法" (#x662600)> ?
很顯然, 它們返回的對象類型不一樣, 一個是 NS-CONSTANT-STRING , 一個是 NS-MUTABLE-STRING.
所有代碼形如:
(in-package "CL-USER") (require "COCOA") (defclass window-view (ns:ns-view) () (:metaclass ns:+ns-object)) (objc:defmethod (#/drawRect: :void) ((self window-view) (rect :<NSR>ect)) (#/set (#/blueColor ns:ns-color)) (#_NSRectFill (#/bounds self))) (defun show-window () (ccl::with-autorelease-pool (let* ((rect (ns:make-ns-rect 0 0 350 350)) (w (make-instance 'ns:ns-window :with-content-rect rect :style-mask (logior #$NSTitledWindowMask #$NSClosableWindowMask #$NSMiniaturizableWindowMask) :backing #$NSBackingStoreBuffered :defer t))) (#/setTitle: w (ccl::%make-nsstring "這是使用中文字符串的簡單方法")) (#/setContentView: w (#/autorelease (make-instance 'window-view))) (#/center w) (#/orderFront: w nil) (#/contentView w)))) (show-window)
而後再次運行, 截圖以下:
是否是很簡單. :)
以上的示例代碼能夠做爲一個簡單的用 Lisp 寫蘋果 APP 程序的窗口模板, 你能夠慢慢本身添加一些其餘的功能, 很快就能獲得一個不太大可是可以提供一些簡單功能的 APP 程序了!