dictionaryWithContentsOfFile:
パスで指定するファイルからキーと値を割り当てて、辞書を作って返します
+(id)dictionaryWithContentsOfFile:(NSString *)path
解説
パスで指定するファイルからキーと値を割り当てて、辞書を作って返します。
パスは、絶対パスでも相対パスでもいいです。
ファイルが無かったり、ファイルから辞書が作れなかったらnilを返します。
このオブジェクトが変更可能でも、この辞書に含まれるオブジェクトは変更不可です。
ファイルの内容は、NSString、NSData、NSDate、NSNumber、NSArray、NSDictionaryだけを含まなければなりません。
フレームワーク
Foundation
クラス
NSDictionary
使用可能
OS X 10.0以降
iOS2.0以降
参照
- initWithContentsOfFile:
例文
#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 ) } }