user3312008
user3312008

Reputation: 3

Load file string names into an array from Documents Directory

I want to add a list of Files in Document Directory to an Array of Strings. Not sure exactly how to do this, this is what I have so far. I want to load/store only the files that contain the word 'bottom' in the filename in the array. How do i do this exactly?

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSFileManager *fileMan = [[NSFileManager alloc]init];
NSArray *files = [fileMan contentsOfDirectoryAtPath:documentsDirectory error:nil];

for(int i =0; i<files.count; i++){

}
NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString rangeOfString:@"bottom"]];


//THIS IS HARDCODED ARRAY OF FILE-STRING NAMES
  NSArray *bottomArray =[NSArray arrayWithObjects: @"bottom6D08B918-326D-41E1-8A47-B92F80EF07E5-1240-000005EB14009605.png", @"bottom837C95CF-85B2-456D-8197-326A637F3A5B-6021-0000340042C31C23.png", nil];

Upvotes: 0

Views: 167

Answers (2)

jlehr
jlehr

Reputation: 15617

In addition to @rmaddy's approach, another option is to use an instance of NSPredicate to filter the array of file names:

NSArray *filenames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:NULL];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self contains 'bottom'"];
NSArray *matchedNames = [filenames filteredArrayUsingPredicate:predicate];

Upvotes: 1

rmaddy
rmaddy

Reputation: 318934

You need to check each file in the files array:

NSFileManager *fileMan = [NSFileManager defaultFileManager];
NSArray *files = [fileMan contentsOfDirectoryAtPath:documentsDirectory error:nil];

NSMutableArray *bottomArray = [NSMutableArray array];
for (NSString *file in files) {
    if ([file rangeOfString:@"bottom"].location != NSNotFound) {
        [bottomArray addObject:file];
    }
}

Upvotes: 2

Related Questions