12.4. Enumerating Files and Folders
Problem
You either want to enumerate folders within a folder or you want to enumerate the list of files inside a folder. The act of enumerating means that you simply want to find all the folders and/or files within another folder.
Solution
Use the contentsOfDirectoryAtPath:error:
instance
method of the NSFileManager
class as
shown here. In this example, we are enumerating all the files, folders,
and symlinks under our app’s bundle folder:
NSFileManager
*
fileManager
=
[[
NSFileManager
alloc
]
init
];
NSString
*
bundleDir
=
[[
NSBundle
mainBundle
]
bundlePath
];
NSError
*
error
=
nil
;
NSArray
*
bundleContents
=
[
fileManager
contentsOfDirectoryAtPath:
bundleDir
error:
&
error
];
if
([
bundleContents
count
]
>
0
&&
error
==
nil
){
NSLog
(
@"Contents of the app bundle = %@"
,
bundleContents
);
}
else
if
([
bundleContents
count
]
==
0
&&
error
==
nil
){
NSLog
(
@"Call the police! The app bundle is empty."
);
}
else
{
NSLog
(
@"An error happened = %@"
,
error
);
}
Discussion
In some of your iOS apps, you may need to enumerate the contents of a folder. Let me give you an example, in case this need is a bit vague right now. Imagine that the user asked you to download 10 images from the Internet and cache them in your app. You go ahead and save them, let’s say, in the tmp/images/ folder that you manually created. Now the user closes your app and reopens it, and in your UI, you want to display the list of already-downloaded-files in a table view. How can you achieve this? Well, it’s easy. ...
Get iOS 6 Programming Cookbook 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.