NSURL file extension addition etc

khalid soofi picture khalid soofi · Jul 22, 2011 · Viewed 7.7k times · Source

I have received a URL from the savePanel sheet and I would like to do following:

  • Check to see if it has an extension
  • if it does, remove it
  • add a custom extension
  • if it does not, then add a custom extension

Any simple way to do this.. I tried something like following but it does not work

if ( [tmp pathExtension] != @"xxx" )
   path = [tmp stringByAppendingFormat:@"xxx"];

OK... A possible solution as follows

NSString *path;
NSURL *filepath;
fileurl = [sheet URL];
fileurl = [fileurl URLByDeletingPathExtension];
fileurl = [fileurl URLByAppendingPathExtension:@"yyy"];
path = [fileurl path];

Answer

user756245 picture user756245 · Jul 22, 2011

This can be achieved using NSString's methods. Note that for string comparison, you have to use isEqualToString:, not ==, which tests for pointers equality.

About the extension use : -(NSString *)pathExtension;. To remove the extension use -(NSString *)stringByDeletingPathExtension;.

In all cases to add an extension, compose a new string using for example : +(NSString *)stringWithFormat:.

So :

NSString *finalString;
if([[tmp pathExtension] isEqualToString:@"xxx"]) {
    finalString = [tmp stringByDeletingPathExtension];
}
finalString = [NSString stringWithFormat:@"%@.yyy", finalString];