Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if folder is empty, and instantiate file names inside the folder into NSStrings? (iphone cocoa)

Just wondering, how would I check if a particular folder is holding files, and instantiate file names inside the folder into NSStrings? I know of a class called NSFileManager, but I'm not sure how to apply it to suit my objective.

like image 645
Jared Aaron Loo Avatar asked Sep 08 '11 00:09

Jared Aaron Loo


2 Answers

NSArray * files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderLocationString error:nil];
like image 99
SVD Avatar answered Nov 16 '22 00:11

SVD


By default all your custom files and data will be stored in the documents directory in your app. I've put a sample code below to access the default document directory; plus a custom folder you may have in there called 'MyFolderName'

The end result will be an array which has a list of NSString objects of the files or directories in the path you have specified.

//Accessing the default documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

//Appending the name of your custom folder, if you have any
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"MyFolderName"]; 

NSFileManager *fileManager = [NSFileManager defaultManager];

if ([fileManager fileExistsAtPath:path]) { // Directory exists
NSArray *listOfFiles = [fileManager contentsOfDirectoryAtPath:path error:nil];
}

Hope this helps! :)

like image 33
Madhu Avatar answered Nov 15 '22 22:11

Madhu