Search for files
Next we will use a program to combine the knowledge learned above, such as nsstring, nsmutablearray, nsenumerator, and nsfilemanager to operate the file system, such as creating directories, deleting files, moving files, or obtaining file information. In the following example, nsfilemanager is required to create nsdirectoryenumerator to traverse the File hierarchy. The following example is explained through annotations:
# Import <Foundation/Foundation. h>
Int main (INT argc, const char * argv []) {
// Sample code for automatically releasing the pool
NSAID utoreleasepool * Pool = [[NSAID utoreleasepool alloc] init];
// Create an nsfilemanager object through defaultmanager in nsfilemanager
Nsfilemanager * manager;
Manager = [nsfilemanager defamanager manager];
// Specify the directory. stringbyexpandingtildeinpath will "~" Replace it with the Home Directory of the current user.
Nsstring * home;
Home = [@"~ "Stringbyexpandingtildeinpath];
// Pass the path string to the File Manager and obtain the nsdirectoryenumerator object, which stores the hierarchy below the folder
Nsdirectoryenumerator * direnum;
Direnum = [Manager enumeratoratpath: Home];
// Define a variable array object to store matching File Information
Nsmutablearray * files;
Files = [nsmutablearray arraywithcapacity: 42];
Nsstring * filename;
// Define an empty nsstring object. If the retrieved object is nil, it indicates the end. You can jump to the loop.
While (filename = [direnum nextobject]) {
// If the conditions are met, the data is stored in a variable array.
If ([[filename pathextension]
Isequalto: @ "jpg"]) {
[Filesaddobject: Filename];
}
}
// Define the enumerated object
Nsenumerator * fileenum;
Fileenum = [files objectenumerator];
// Print the content in the array in sequence
While (filename = [fileenum nextobject]) {
Nslog (@ "% @", filename );
}
// Automatically release the sample code of the pool for cleanup
[Pool drain];
Return 0;
}