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 开发者_JAVA百科
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];
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];
An alternate approach to the workable solution given on this same page by @user756245 but using different NSString
methods:
NSString *finalString;
if([[tmp pathExtension] isEqualToString:@"xxx"]) {
finalString = [tmp stringByDeletingPathExtension];
}
finalString = [finalString stringByAppendingPathExtension:@"yyy"];
Here is an 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"
精彩评论