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装载视图

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