2012年2月24日 星期五

[objc] 被沒收的 UTF8String

最近協助同事開發 webkit plugin,我提供的 Player 能使用 playWithUrl 啟動播放:

-(void)playWithUrl: (const char*) aUrl;

但在 plugin 由外層 javascript 傳入的參數是 NSString* 型式的,直覺上我們會利用 UTF8String 方法,獲得 c String:

[theUrl UTF8String]

但試了幾次後,發現轉進來的 c String 偶爾會變成奇怪的內容,俗稱『亂碼』。這種偶發性的不確定因素,有股熟悉感。先翻閱手冊,在 UTF8String 中提到:


The returned C string is automatically freed just as a returned object would be released; you should copy the C string if it needs to store it outside of the autorelease context in which the C string is created.

簡單地說,這個 c String 是生命週期會跟著原來的 NSString 跑,所以,要確保它被使用的時候,是正確的內容,我們應該先 retain 它,最後,我們討論了一下,決定提供一個新的 method:

-(void)playWithNSStringUrl: (NSString*) theUrl
{
[theUrl retain];
memset(inputUrl, 0, sizeof(char) * 1024);
strncpy(inputUrl, [theUrl UTF8String], 1024);
[theUrl release];
[self playWithUrl: inputUrl];
}

確實宣示我們持有 theUrl,並保存其內容。亂碼就不再來亂了 :D

沒有留言:

張貼留言