derFalke
derFalke

Reputation: 247

Generate String for file/directory name

I create a directory in the documents directory with the string @"My Folder" by pressing a button. But if this directory already exist I want it to be named @"My Folder 1" and if this exists then @"My Folder 2" and so on.. How can I achieve this?

I test whether the directory already exists with this

if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
    [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil]; 
    else {

}

Upvotes: 2

Views: 103

Answers (1)

Richard J. Ross III
Richard J. Ross III

Reputation: 55563

This should work for what you need.

int i = 0;
while ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"My Folder %i", i])
    i++;
}

NSString *folder = [NSString stringWithFormat:@"My Folder %i", i];
[[NSFileManager createDirectoryAtPath:folder withIntermediateDirectories:NO attributes:nil error:nil];

Upvotes: 2

Related Questions