如何在Mac OS X上將NSTextView
的內容轉換爲NSData
,然後將其轉換並顯示出來?將NSTextView格式的文本轉換爲NSData(和後退)
我可以通過使用textView.textStorage.string
(其中textView是NSTextView
對象)來轉換文本而不進行格式設置。但是,我想保存文本格式。
事實上,我已經實施了一種可行的方法,但我不確定它總是能夠正常工作。我編碼NSTextStorage
對象本身並寫入它,然後將它讀回爲NSAttributedString
。 (NSTextStorage
是NSAttributedString
的一個子類。)我這樣做是因爲我無法直接爲NSTextView
設置textStorage
,但我可以設置它的屬性字符串。
這裏是我的代碼轉換它(結果是data
):
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:textView.textStorage forKey:@"attrs"];
[archiver finishEncoding];
讀回:
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
NSAttributedString* theAttrString = [unarchiver decodeObjectForKey:@"attrs"];
[unarchiver finishDecoding];
,並顯示它:
[textView.textStorage setAttributedString:theAttrString];
這種方法保證工作,因爲我編碼了一個NSTextStorage
對象並將它讀回來把它解釋爲NSAttributedString
?
我不明白爲什麼不。這似乎是一個完全有效的序列化方法。然而,這個問題「這是一個好方法嗎?」有點主觀,所以這裏可能不是最好的問題。 –
謝謝 - 我已經編輯了最後一個問題,使其不那麼主觀。 –