Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS create file

Tags:

ios

createfile

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).

like image 846
Nick Avatar asked Jan 16 '12 13:01

Nick


1 Answers

NSFileHandle might not have a method to create a file, but NSFileManager has one. Have you looked at that class?

This works fine for me, however note that it will overwrite the same file each time

NSString *cachesFolder = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *file = [cachesFolder stringByAppendingPathComponent:@"testfile"];    
[[NSData data] writeToFile:file options:NSDataWritingAtomic error:nil];
like image 127
bandejapaisa Avatar answered Sep 22 '22 17:09

bandejapaisa