Search for file name with template in iPhone SDK

I am trying to write a program that creates dynamically named .csv files that must either be restored or deleted at a later launch date. I am trying to do the following:

I would like to run an algorithm that will detect if any of these file types exist. For example, if I dynamically named a file something like foobar ##. Csv C ##, indicating the number that is dynamically generated and added to the file name, I would like to find if any foobar ## file exists. Csv regardless of used number. Normally I would use a line of code:

NSString *dataFileName = [[self documentPath] stringByAppendingPathComponent:@"foobar01.csv"]; 

For the moment, I just use a loop that loops through each value cyclically and sends bool if it is found, but I know that this is not the best practice, since it limits the possible file name numbers that the user can use. Any insight into how I can use some kind of template for a search like this would be greatly appreciated.

In addition, I would like to create a method that will delete any .csv files found by the program, but I assume that the method used to solve the above algorithm can also be used to delete.

+4
source share
3 answers

Wildcard For wildcard matching, the query can be used as a substitute for the comparison operator and include "*" (matching zero or more characters) or "?" (matches exactly 1 character) as wildcard as follows:

 NSString *match = @"imagexyz*.png"; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF like %@", match]; NSArray *results = [directoryContents filteredArrayUsingPredicate:predicate]; 

http://useyourloaf.com/blog/2010/7/27/filtering-arrays-with-nspredicate.html

+5
source

See NSFileManagers contentsOfDirectoryAtPath:error: It will return an array with strings containing the names of all objects (files and directories) of the corresponding directory.

You can then list this array and check for the presence of "foobar" in these lines. Either do something in the files that you found immediately, or save the β€œpositive” file names in another array for later processing.

+2
source

code example for which another poster said more or less.

 +(NSMutableArray*) allocLocalFiles { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSError * error = nil; NSArray *origContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:&error]; NSMutableArray * files = [[NSMutableArray alloc]init]; for (NSString* file in origContents) { NSString * ext = [file pathExtension]; if ([ext compare:@"csv"]==0 && something_else) { [files addObject: [NSString stringWithFormat:@"%@/%@",documentsDirectory,file]]; } } return files; } 
0
source

Source: https://habr.com/ru/post/1342002/


All Articles