14.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:
-
(
BOOL
)
application:
(
UIApplication
*
)
application
didFinishLaunchingWithOptions:
(
NSDictionary
*
)
launchOptions
{
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
);
}
self
.
window
=
[[
UIWindow
alloc
]
initWithFrame:
[[
UIScreen
mainScreen
]
bounds
]];
// Override point for customization after application launch.
self
.
window
.
backgroundColor
=
[
UIColor
whiteColor
];
[
self
.
window
makeKeyAndVisible
];
return
YES
;
}
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 ...
Get iOS 7 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.