Sunday, May 19, 2013

NSString pathExtension example ios

[NSString pathExtension]

Interprets the receiver as a path and returns the receiver’s extension, if any.
- (NSString *)pathExtension
Return Value
The receiver’s extension, if any (not including the extension divider).
Discussion of [NSString pathExtension]
The path extension is the portion of the last path component which follows the final period, if there is one. The following table illustrates the effect of pathExtensionon a variety of different paths:
Receiver’s String Value
String Returned
/tmp/scratch“” (an empty string)
/tmp/“” (an empty string)
Note that this method only works with file paths (not, for example, string representations of URLs).
Example of [NSString pathExtension]
NSString* initPath = ...
NSString *newPath = [[NSString stringWithFormat:@"%@/%@",
                    [initPath stringByDeletingLastPathComponent], newFileName] 
                     stringByAppendingPathExtension:[initPath pathExtension]];
Example of [NSString pathExtension]
NSString *pathToFile = @"/Path/To/File.txt";
NSString *oldFileName = [pathToFile lastPathComponent];
NSString *newFileName = [@"Document" stringByAppendingPathExtension:[oldFileName pathExtension];
NSString *newPathToFile = [pathToFile stringByDeletingLastPathComponent];
[newPathToFile stringByAppendingString:newFileName];
Example of [NSString pathExtension]
@interface NSString (MoreMagic)
- (NSString *)stringByAddingFileSuffix:(NSString *)suffix;

@implementation NSString (MoreMagic)
- (NSString *)stringByAddingFileSuffix:(NSString *)suffix
    NSString * extension = [self pathExtension];
    NSString * baseName = [self stringByDeletingPathExtension];
    NSString * thumbBase = [baseName stringByAppendingString:suffix];
    return [thumbBase stringByAppendingPathExtension:extension];