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 omitted
To 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 ...
Get Programming iOS 6, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.