开发者

NSString issues

I have an NSString that gets assigned a string value. How do I take this NSString and insert @"-thumbnail" between th开发者_运维知识库e file's name and its extension?

In other words, how do I go from:

NSString *fileName = @"myFile.png";

to:

NSString *thumbnailName = [NSString someMagicFunction...]
NSLog(@"%@", thumbnailName);  // Should Output "myFile-thumbnail.png"


The NSString additions for path components can come in handy, specifically: pathExtension and stringByDeletingPathExtension

Edit: see also: stringByAppendingPathExtension: (as pointed out by Dave DeLong)

NSString * ext = [fileName pathExtension];
NSString * baseName = [fileName stringByDeletingPathExtension];
NSString * thumbBase = [baseName stringByAppendingString:@"-thumbnail"];
NSString * thumbnailName = [thumbBase stringByAppendingPathExtension:ext];

If you really want that magicFunction to exist, you can add a category method to NSString like so:

@interface NSString (MoreMagic)
- (NSString *)stringByAddingFileSuffix:(NSString *)suffix;
@end

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

To be used as follows:

NSString * thumbnailName = [fileName stringByAddingFileSuffix:@"-thumbnail"];


If you are certain of your filenames, you could also simply do:

[NSString stringByReplacingOccurrencesOfString:@"." withString:@"-thumbnail."]

But the path handling stuff is cleaner (doesn't care how many "." you have in the name) and good to know about for trickier cases.


We've got an opensource category for just that: -[NSString ks_stringWithPathSuffix:]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜