2011-03-12 31 views
1

我正在嘗試爲Mac OS X創建一個簡單的文本編輯器,如Textedit,但經過許多小時的研究後,無法弄清楚如何將文檔的數據正確寫入文件。我使用Cocoa框架,我的應用程序是基於文檔的。展望可可API在我周圍發現了一個簡短的教程,「建設在15分鐘內用文本編輯器」或這樣的事情,實現以下方法將數據寫入文件:如何使用指定的NSString編碼在Cocoa中保存文本文檔?

- (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; 
} 

這只是正常工作,但我想讓用戶選擇文本編碼。我想這種方法使用「自動」編碼,但我怎樣才能使用預定義的編碼寫入數據?我嘗試使用以下代碼:

- (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是-1,如果用戶沒有設置特定的編碼,在[的NSString availableStringEncodings]列出的編碼的其他方式之一。但是,無論何時我嘗試使用與UTF8不同的編碼保存文檔,應用程序都會崩潰。同樣的情況,當我嘗試我的文檔編碼用下面的代碼:

NSString *string=[[textView textStorage] string]; 
data=[string dataUsingEncoding:saveEncoding]; 

我在做什麼錯?如果有人知道Textedit如何解決這個問題,這將是非常棒的。

回答

1

也許你還記得NSDictionary中只能存儲對象...

NSMutableDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: 
    NSPlainTextDocumentType, 
    NSDocumentTypeDocumentAttribute, 
    [NSNumber numberWithInteger:saveEncoding], 
    NSCharacterEncodingDocumentAttribute, 
    nil]; 
+0

非常感謝你,這是很顯然......反正現在一切工作正常! ;-) – Nickkk 2011-03-12 11:15:18

相關問題