How to prevent the user to rummage the file extension


I’d like to prevent my user to enter a wrong file extension into the NSSavePanel. This is how:

NSString *thePath = [[[NSString stringWithString:[[op URL]path]]stringByDeletingPathExtension]stringByAppendingPathExtension:@“evals7”]; // normalize file name.

So, if (s)he enters “Toto” I get “Toto.evals7”, if (s)he enters “Toto.evals” I get “Toto.evals7”.

Is there a better way to do it?

I don’t now a better way, but the stringWithString part isn’t necessary --[[op URL] path] returns a string.


Your stringWithString: is redundant. I think it would be safer to check the extension, and if it’s wrong add the correct one. But setting allowedFileTypes and setting allowsOtherFileTypes to NO effectively does that for you.

That is:
NSSavePanel *op = [NSSavePanel savePanel];
[op setAllowedFileTypes:[NSArray arrayWithObject:@“evals7”]];
[op setAllowsOtherFileTypes:NO];
[op runModal];

Yes, the difference is, for the example above, I could end with “Toto.evals.evals7”. Well, it was just to be sure, a “standard” user does not even know what an extension is.


If you provide a name like Untitled.eval7, the Untitled part only will be selected. But there’s always setExtensionHidden: and setCanSelectHiddenExtension: if you want to be doubly-sure.