7

I am trying to open a file for writing into it. The file may not exist.

I found that [NSFileHandle fileHandleForWritingAtPath:filePath] returns nil if file does not exist. Having googled, I found code snippets like this

[[NSData data] writeToFile:filePath atomically:YES]

which, I guess, ensures file existance before opening it.

My questions is: is the latter code line recommended way of file creation? It seems strange that NSFileHandle has no routine to create a new file (and only can deal with existing files).

4

2 に答える 2

14

NSFileHandleファイルを作成するメソッドがないかもしれませんが、NSFileManager1 つがあります。そのクラスを見たことがありますか?

これは私にとってはうまくいきますが、毎回同じファイルを上書きすることに注意してください

NSString *cachesFolder = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *file = [cachesFolder stringByAppendingPathComponent:@"testfile"];    
[[NSData data] writeToFile:file options:NSDataWritingAtomic error:nil];
于 2012-01-16T13:49:45.773 に答える
0

In Swift 4.x & 5.0, you can do it like this:

let yourData = Data() // the data to write

let cachesFolderPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first

if let path = cachesFolderPath {
    let url = URL(fileURLWithPath: path).appendingPathComponent("xxx-cache")
    do {
        try yourData.write(to: url)
    } catch {
        print("writing failed: \(error.localizedDescription)")
    }
}
于 2019-04-30T03:25:48.177 に答える