views:

12

answers:

1

What's the simplest way to add a suffix to a file name before the extension in Objective-C?

Example

  • Original name: image.png
  • Suffix: ~ipad
  • Result: image~ipad.png
A: 

NSString has a whole bunch of path-related methods:

NSString* appendSuffixToPath(NSString * path, NSString * suffix) {
   NSString * containingFolder = [path stringByDeletingLastPathComponent];
   NSString * fullFileName = [path lastPathComponent];
   NSString * fileExtension = [fullFileName pathExtension];
   NSString * fileName = [fullFileName stringByDeletingPathExtension];
   NSString * newFileName = [fileName stringByAppendingString:suffix];
   NSString * newFullFileName = [newFileName stringByAppendingPathExtension:fileExtension];
   return [containingFolder stringByAppendingPathComponent:newFullFileName];
}

(Yes, you could do that with a lot fewer variables, but I wanted to make it clear what each method was doing)

Dave DeLong
Thanks Dave! I suspected there was something like stringByDeletingPathExtension available in Obj-C.
hgpc