I'm trying to create a simple text editor like Textedit for Mac OS X, but after many hours of research can't figure out how to correctly write my document's data to a file. I'm using the Cocoa framework and my application is document-based. Looking around in the Cocoa API I found a brief tutorial, "Building a text editor in 15 minutes" or something like this, that implements the following method to write the data to a file:
- (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError {
[textView breakUndoCoalescing];
NSAttributedString *string=[[textView textStorage] copy];
NSData *data;
NSMutableDictionary *dict=[NSDictionary dictionaryWithObject:NSPlainTextDocumentType forKey:NSDocumentTypeDocumentAttribute];
data=[string dataFromRange:NSMakeRange(0,[string length]) documentAttributes:dict error:outError];
return data;
}
This just works fine, but I'd like to let the user choose the text encoding. I guess this method uses an "automatic" encoding, but how can I write the data using a predefined encoding? I tried using the following code:
- (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError {
[textView breakUndoCoalescing];
NSAttributedString *string=[[textView textStorage] copy];
NSData *data;
NSInteger saveEncoding=[prefs integerForKey:@"saveEncoding"];
// if the saving encoding is set to "automatic"
if (saveEncoding<0) {
NSMutableDictionary *dict=[NSDictionary dictionaryWithObject:NSPlainTextDocumentType forKey:NSDocumentTypeDocumentAttribute];
data=[string dataFromRange:NSMakeRange(0,[string length]) documentAttributes:dict error:outError];
// else use the encoding specified by the user
} else {
NSMutableDictionary *dict=[NSDictionary dictionaryWithObjectsAndKeys:NSPlainTextDocumentType,NSDocumentTypeDocumentAttribute,saveEncoding,NSCharacterEncodingDocumentAttribute,nil];
data=[string dataFromRange:NSMakeRange(0,[string length]) documentAttributes:dict error:outError];
}
return data;
}
saveEncoding is -1 if the user didn't set a specific encoding, otherwise one of the encodings listed in [NSString availableStringEncodings]. But whenever I try to save my document in a different encoding from UTF8, the app crashes. The same happens when I try to encode my document with the following code:
NSString *string=[[textView textStorage] string];
data=[string dataUsingEncoding:saveEncoding];
What am I doing wrong? It would be great if someone knows how Textedit solved this problem.