macOS/iOS API解説

iOS , Mac アプリケーション開発のために使われる主要フレームワークの日本語情報です。2010年代に書かれた内容です。今後更新はありません。

目次

initWithContentsOfFile:usedEncoding:error:

INDEX>Foundation>NSString>

指定したファイルの内容をで初期化して返します
-(id)initWithContentsOfFile:(NSString *)path
             usedEncoding:(NSStringEncoding *)enc
             error:(NSError **)error

解説

指定したファイルの内容を初期化して返します。
10.4以降はstringWithContentsOfFile:を使わず、このメソッドを使います。

返り値

( id )

オブジェクト()

引数

( NSString * )path

ファイルパス

( NSStringEncoding * )enc

推測されるエンコード

( NSError ** )error

エラーを返すエラーオブジェクト

クラス

NSString

Instance Methods

使用可能

10.4

参照

+stringWithContentsOfFile:encoding:error:
-initWithContentsOfFile:encoding:error:

例文

#pragma mark initWithContentsOfFile:usedEncoding:error:
- (void)displayText032:(NSString *)text {
	self.fileString = text;
    NSLog(@"text %@",text);
}
-(void)method032
{
    //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;
            NSStringEncoding encoding = 0;
            
            NSString *output = [[NSString alloc] initWithContentsOfFile:[theDoc path] usedEncoding: &encoding
                                                            error: &error];
            [self performSelectorOnMainThread:@selector(displayText032:) withObject:output waitUntilDone:NO];
            
            
            
            switch (encoding) {
                case NSASCIIStringEncoding:
                    NSLog(@"NSASCIIStringEncoding");
                    break;
                case NSNEXTSTEPStringEncoding:
                    NSLog(@"NSNEXTSTEPStringEncoding");
                    break;
                case NSJapaneseEUCStringEncoding:
                    NSLog(@"NSJapaneseEUCStringEncoding");
                    break;
                case NSUTF8StringEncoding:
                    NSLog(@"NSUTF8StringEncoding");
                    break;    
                default:
                    NSLog(@"%lu",encoding);
                    break;
            }
            
        }
    }];
    
    
}