-writeToFile:atomically:
pathで指定したファイルに書き込みます
-(BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag
解説
pathで指定したファイルに書き込みます。pathが~を含む場合はまずstringByExpandingTildeInPathを使って、絶対パスにしなければなりません。
flagがYESなら、元ファイルを残し、書き終わってからリネームします。
レシーバの内容がプロパティリストで有効なオブジェクト(NSString、NSData、NSArray、NSDictionary)なら、arrayWithContentsOfFileやinitWithContentsOfFileでNSArrayを作ることができるファイルになります。
ファイルの操作はURLを使うことが推奨されていますのでwriteToURL:atomically:を使うほうが良いでしょう。
返り値
( BOOL )
書き込めたかYES/NO
フレームワーク
Foundation
クラス
NSArray
Instance Methods
使用可能
10.0
iOS2.0
例文
#pragma mark writeToFile:atomically: -(void)method023 { //書き込み用のNSArrayを作成 NSArray *anArray = [NSArray arrayWithObjects:@"file",[NSNumber numberWithFloat:3.0],@"bbb",@"ccc",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:@"plistfile3.plist" contents:dat1 attributes:dic]; NSLog(@"myFile path = %@",[myFile currentDirectoryPath]); NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"plistfile3" ofType:@"plist"]; //書き込み [anArray writeToFile:resourcePath atomically:YES]; //ファイルから読み込んで、NSArrayを作成 NSArray *readArray = [NSArray arrayWithContentsOfFile:resourcePath]; NSLog(@"%s : %@", __FUNCTION__,[readArray description]); //=>[OOOAppDelegate method023] : (file,3,bbb,ccc) }
#import "MyObject.h" @implementation MyObject - (IBAction)myAction:(id)sender { NSArray *arr = [NSArray arrayWithObjects:@"aaa",@"bbb",@"ccc",nil]; //testWriteArray.txtのファイルが警告無しで書き変わるので注意!!!! NSString *str1 = @"~/testWriteArray.txt"; if ([arr writeToFile:[str1 stringByExpandingTildeInPath] atomically:YES]){ NSLog(@"YES"); } else{ NSLog(@"NO"); } } @end