stringWithContentsOfFile:encoding:error:
指定したファイルの内容から指定したエンコーディングで文字列を返します
+(id)stringWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error
解説
指定したファイルの内容から指定したエンコーディングで文字列を返します。
10.4以降はstringWithContentsOfFile:を使わず、このメソッドを使います。
【NSStringEncoding】
● NSASCIIStringEncoding 7ビットASCIIエンコード
● NSNEXTSTEPStringEncoding NeXTSTEP拡張8ビットASCIIエンコード
● NSJapaneseEUCStringEncoding 日本語EUC
● NSUTF8StringEncoding 8ビットUnicode(UTF8)エンコード
● NSISOLatin1StringEncoding ISOラテン1エンコード
● NSISOLatin2StringEncoding ISOラテン2エンコード
● NSSymbolStringEncoding シンボルエンコード
● NSNonLossyASCIIStringEncoding 損失無し7ビットASCIIエンコード
● NSShiftJISStringEncoding シフトJIS
● NSUnicodeStringEncoding Unicodeエンコード
● NSWindowsCP1251StringEncoding アドビスタンダードCyrillic
● NSWindowsCP1252StringEncoding Winラテン1
● NSWindowsCP1253StringEncoding Greek
● NSWindowsCP1254StringEncoding Turkish
● NSWindowsCP1250StringEncoding Winラテン1
● NSISO2022JPStringEncoding ISO2022日本語エンコード(電子メールなど)
● NSMacOSRomanStringEncoding MacRoman
● NSProprietaryStringEncoding
返り値
( id )
オブジェクト(NSStringかそのサブクラス)
フレームワーク
Foundation
クラス
NSString
Class Methods
使用可能
10.4
参照
-initWithContentsOfFile:encoding:error:
例文
#pragma mark stringWithContentsOfFile:encoding:error: - (void)displayText029:(NSString *)text { self.fileString = text; NSLog(@"text %@",text); } -(void)method029 { //FileSystem programming guide //http://developer.apple.com/library/ios/#DOCUMENTATION/FileManagement/Conceptual/FileSystemProgrammingGUide/UsingtheOpenandSavePanels/UsingtheOpenandSavePanels.html //OpenPanelを作る NSOpenPanel *opPanel = [ NSOpenPanel openPanel ]; //OpenPanelでファイル選択 //This way is 10.6 or later [opPanel setCanChooseDirectories:YES]; [opPanel setAllowsMultipleSelection:YES]; [opPanel setPrompt:NSLocalizedString(@"prompt text", nil)]; [opPanel setMessage:@"Message"]; [opPanel beginWithCompletionHandler:^(NSInteger result){ if (result == NSFileHandlingPanelOKButton) { NSURL* theDoc = [[opPanel URLs] objectAtIndex:0]; // Open the document. NSError *error = nil; NSString *output = [NSString stringWithContentsOfFile:[theDoc path] encoding: NSASCIIStringEncoding error: &error]; [self performSelectorOnMainThread:@selector(displayText029:) withObject:output waitUntilDone:NO]; } }]; }
#import "SetImage.h" @implementation SetImage - (IBAction)set:(id)sender { //開けるファイル拡張子の配列 NSArray *fileTypes = [ NSArray arrayWithObject : @"txt" ]; //OpenPanelを作る NSOpenPanel *opPanel = [ NSOpenPanel openPanel ]; // //NSString *str; //OpenPanelの結果のボタン番号 int opRet; //OpenPanelでファイル選択 opRet = [ opPanel runModalForDirectory : NSHomeDirectory() //どこのディレクトリを出すか file : @"Documents" //どのファイルを選択しておくか types : fileTypes ];//選べるファイルタイプ if ( opRet == NSOKButton ) { // OPENPanelのボタンがOKなら //ファイルから読み込む NSError *error = nil; NSString *newString = [NSString stringWithContentsOfFile:[opPanel filename] encoding: NSASCIIStringEncoding error: &error ]; [name setStringValue: newString ]; } } @end