Adding NSURL extension, etc.

I got the url from savePanel sheet, and I would like to do the following:

  • Check if it has an extension
  • if so remove it
  • add custom extension
  • If not, add a custom extension

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

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

OK ... Possible solution as follows

 NSString *path; NSURL *filepath; fileurl = [sheet URL]; fileurl = [fileurl URLByDeletingPathExtension]; fileurl = [fileurl URLByAppendingPathExtension:@"yyy"]; path = [fileurl path]; 
+8
objective-c nsstring nsurl
source share
3 answers

This can be achieved using NSString methods. Note that to compare strings you should use isEqualToString: rather than == , which checks for equality of pointers.

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

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

So:

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

An alternative approach to the working solution presented on the same page using @ user756245, but using different NSString methods:

 NSString *finalString; if([[tmp pathExtension] isEqualToString:@"xxx"]) { finalString = [tmp stringByDeletingPathExtension]; } finalString = [finalString stringByAppendingPathExtension:@"yyy"]; 
+1
source share

Here is the update for Swift 4.1 using URL

 // assuming you are building an URL from string let url = URL(string: "file.abc")! let finalUrl = url.deletingPathExtension().appendingPathExtension("mp3") let finalString = finalUrl.path // output "file.mp3" 
0
source share

All Articles