14.3. Creating Folders on Disk
Problem
You want to be able to create folders on disk to save some of your app’s files in them.
Solution
Use the createDirectoryAtPath:withIntermediateDirectories:attributes:error:
instance method of the NSFileManager
class, as shown here:
-(BOOL)application:(UIApplication*)applicationdidFinishLaunchingWithOptions:(NSDictionary*)launchOptions{NSFileManager*fileManager=[[NSFileManageralloc]init];NSString*tempDir=NSTemporaryDirectory();NSString*imagesDir=[tempDirstringByAppendingPathComponent:@"images"];NSError*error=nil;if([fileManagercreateDirectoryAtPath:imagesDirwithIntermediateDirectories:YESattributes:nilerror:&error]){NSLog(@"Successfully created the directory.");}else{NSLog(@"Failed to create the directory. Error = %@",error);}self.window=[[UIWindowalloc]initWithFrame:[[UIScreenmainScreen]bounds]];self.window.backgroundColor=[UIColorwhiteColor];[self.windowmakeKeyAndVisible];returnYES;}
Discussion
The APIs exposed by NSFileManager are very easy to use, and it’s
no surprise that you can use them to create folders on disk in a few
lines. The createDirectoryAtPath:withIntermediateDirectories:attributes:error:
method may look scary at first, but it’s not that bad. I will explain
the different parameters that you can pass to it:
createDirectoryAtPathThe path to the folder that has to be created.
withIntermediateDirectoriesA Boolean parameter that, if set to
YES, will create all the folders in the middle ...
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