macOS學習筆記(8)簡易富文本編輯器

直接貼代碼:

#import <Cocoa/Cocoa.h>

@interface MyDocument : NSDocument
{
	IBOutlet NSTextView *textView;
	NSAttributedString * rtfData;//帶屬性的字符串對象
}
@end

#import "MyDocument.h"

@implementation MyDocument

- (id)init
{
    self = [super init];
    if (self) {
    
        // Add your subclass-specific initialization here.
        // If an error occurs here, send a [self release] message and return nil.
    
    }
    return self;
}

- (NSString *)windowNibName
{
    // Override returning the nib file name of the document
    // If you need to use a subclass of NSWindowController or if your document supports multiple NSWindowControllers, you should remove this method and override -makeWindowControllers instead.
    return @"MyDocument";
}

- (void)windowControllerDidLoadNib:(NSWindowController *) aController
{
    [super windowControllerDidLoadNib:aController];
    // Add any code here that needs to be executed once the windowController has loaded the document's window.

	if(rtfData){
		[[textView textStorage] replaceCharactersInRange:NSMakeRange(0, [[textView string] length]) withAttributedString:rtfData];
		[rtfData release];
	}
	[textView setAllowsUndo:YES];
}

-(Boolean)readFromFileWrapper:(NSFileWrapper *)fileWrapper ofType:(NSString *)typeName error:(NSError **)outError
{
	rtfData=[[NSAttributedString alloc] initWithRTF:[wrapper regularFileContents] documentAttributes:nil];
	if(textView){
		[[textView textStorage] replaceCharactersInRange:NSMakeRange(0, [[textView string] length]) withAttributedString:rtfData];
		[rtfData release];
	}
	return YES;
}
-(NSFileWrapper*)fileWrapperOfType:(NSString *)typeName error:(NSError **)outError
{
	NSRange range=NSMakeRange(0, [[textView string] length]);
	NSFileWrapper * wrapper=[[NSFileWrapper alloc] initRegularFileWithContents:[textView RTFFromRange:range]];
	return [wrapper autorelease];
}
@end

###回顧基本概念

一個基於文本處理的程序被描述成一個NSDocument Controller對象的實例,它可以控制多個NSDocument對象,每一個對象即對應一個文本,這個對象一般具有以下4個功能:

  1. 爲程序其他對象提供文檔的數據表達
  2. 裝載數據到內部數據結構並顯示在窗口中
  3. 把文檔數據存儲到文件
  4. 讀取文檔數據
    然後,NSDocument控制NSWindowController控制視圖view。

對比普通文本編輯器的區別,統一解釋:
普通文本編輯器:
5. 用readFromData方法從文件系統中讀出一個NSData
6. 用dataOfType把NSData變成NSString
7. windowControllerDidLoadNib把文本數據裝載到文本視圖中

富文本編輯器:
8. readFromFileWrapper從文件夾裏讀數據
9. fileWrapperOfType使文檔能保存富文本內容
10. windowControllerDidLoadNib裝載視圖

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章