0

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];
0

2 Answers 2

2

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];
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

ok thank you, that works, but now i am trying to load an image from that string file name, and it was working with the hard coded code but now it doesn't work with this - it keeps saying breakpoint thread 1 , not really sure why this line of code below isnt working now.. any thoughts/suggestions/corrections ? NSString *path = [documentsDirectory stringByAppendingPathComponent:[[NSString stringWithFormat: [bottomArray objectAtIndex:i]]]];
That's because i isn't there in my answer. You already have file, use it to build the path.
i have no idea how to do that or what that means.. i just want bottomArray[i]
i want to have a loop that loads images from document directory one at a time... where i=0 until files.count then start all over again with i=0
1

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];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.