macOS/iOS API解説

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

目次

dictionaryWithContentsOfFile:

INDEX>Foundation>NSDictionary

パスで指定するファイルからキーと値を割り当てて、辞書を作って返します

Objective-C

+(id)dictionaryWithContentsOfFile:(NSString *)path

Swift


解説

パスで指定するファイルからキーと値を割り当てて、辞書を作って返します。
パスは、絶対パスでも相対パスでもいいです。
ファイルが無かったり、ファイルから辞書が作れなかったらnilを返します。
このオブジェクトが変更可能でも、この辞書に含まれるオブジェクトは変更不可です。

ファイルの内容は、NSString、NSData、NSDate、NSNumber、NSArray、NSDictionaryだけを含まなければなりません。

返り値

Objective-C

( id )

Swift


作った辞書

引数

Objective-C

( NSString * )path

Swift

ファイルのパス。フルパスでも相対パスでもかまいません。
プロパティリストとして表現される形式で、ルートは辞書でなければなりません。

クラス

NSDictionary

使用可能

OS X 10.0以降
iOS2.0以降

参照

- initWithContentsOfFile:

例文

Objective-C

#pragma mark NSDictionary dictionaryWithContentsOfFile:
-(void)method002
{
    //書き込み用のNSDictionaryを作成
    NSDictionary *aDictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"aaa",@"key1",@"bbb",@"key2",@"ccc",@"key3", nil];
    
    //メインバンドル内のResourceにplistfile2.plistファイルを作成
    NSFileManager *myFile = [ NSFileManager defaultManager];
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:
                         [NSDate date],NSFileModificationDate,
                         @"owner",@"NSFileOwnerAccountName",
                         @"group",@"NSFileGroupOwnerAccountName",
                         nil,@"NSFilePosixPermissions",
                         [NSNumber numberWithBool:YES],@"NSFileExtensionHidden",
                         nil];
    
    NSMutableData *dat1 = [[NSMutableData alloc] initWithCapacity:1];
    
    [myFile changeCurrentDirectoryPath:[[[NSBundle mainBundle] resourcePath] stringByExpandingTildeInPath]];
    [myFile createFileAtPath:@"plistfile2.plist" contents:dat1 attributes:dic];
    NSLog(@"myFile path = %@",[myFile currentDirectoryPath]);
    
    NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"plistfile2" ofType:@"plist"];
    NSURL *url = [NSURL fileURLWithPath:resourcePath];
    //書き込み
    [aDictionary writeToURL:url atomically:YES];
    
    //ファイルから読み込んで、NSDictionaryを作成
    NSDictionary *readDictionary = [NSDictionary dictionaryWithContentsOfFile:resourcePath];
    NSLog(@"%s %p = %@",__FUNCTION__,readDictionary,[readDictionary description]);
    
    //=>-[OOOAppDelegate method002] 0x6d653d0 = {key1 = aaa;key2 = bbb;key3 = ccc;}
}
//NSDictionary
    @IBAction func function001(sender: AnyObject) {
        var aDict: NSDictionary?
        if let path = NSBundle.mainBundle().pathForResource("TESTDICTIONARY", ofType: "plist"){
            aDict = NSDictionary(contentsOfFile: path)
        }
        if let dict = aDict {
            NSLog("%@",dict.description )
        }
        
    }