Basic File Operations
Let’s say we intend to create folder MyFolder inside the Documents directory. Assume that we have an NSFileManager instance fm and an NSURL docsurl pointing at the Documents directory, as shown in the previous section. We can then generate a reference to MyFolder; we can then ask our NSFileManager instance to create the folder if it doesn’t exist already:
NSURL* myfolder = [docsurl URLByAppendingPathComponent:@"MyFolder"];
NSError* err = nil;
BOOL ok =
[fm createDirectoryAtURL:myfolder
withIntermediateDirectories:YES attributes:nil error:nil];
// ... error-checking omittedTo learn what files and folders exist within a directory, you can ask for an array of the directory’s contents:
NSError* err = nil;
NSArray* arr =
[fm contentsOfDirectoryAtURL:docsurl
includingPropertiesForKeys:nil options:0 error:&err];
// ... error-checking omitted
NSLog(@"%@", [arr valueForKey:@"lastPathComponent"]);
/*
MyFolder
*/The array resulting from contentsOfDirectoryAtURL:... lists full URLs of the directory’s immediate contents; it is shallow. For a deep array, which might be very big, you can enumerate the directory, so that you are handed only one file reference at a time:
NSDirectoryEnumerator* dir =
[fm enumeratorAtURL:docsurl
includingPropertiesForKeys:nil options:0 errorHandler:nil];
for (NSURL* f in dir)
if ([[f pathExtension] isEqualToString: @"txt"])
NSLog(@"%@", [f lastPathComponent]);
/*
file1.txt
file2.txt
*/A directory enumerator also permits you to decline to dive into ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access