macOS/iOS API解説

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

目次

-writeToFile:atomically:

INDEX>Foundation>NSArray

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

引数

( NSString * )path

ファイルパス文字列(絶対パス

( BOOL )flag

安全に書き込むかYES/NO

クラス

NSArray

Instance Methods

使用可能

10.0
iOS2.0

例文

iOS

#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

編集時のバージョン

OS X 10.8
iOS 7.0