case insensitive checking of suffix of NSString

compare, nsstring, objective-c

Solution

If `selectedFile` is a filename, it's best to look at the entire extension. It's unlikely but possible that you'll find a file titled ThisIsNotAnImage.asdfjpg. If you just check the suffix, you'll incorrectly conclude that this is an image.

Fortunately `NSString` has many methods for working with paths, including `pathExtension`.

Also, do you want to always and only accept JPEG images, or all images that you can load? Most of Apple's image classes support an impressive range of file formats.

If you're writing for iOS, the image formats recognised by `UIImage` are listed in the UIImage Class Reference, along with their extensions.

If you're writing for Mac OS, `NSImage` has a class method called `imageFileTypes`, allowing the formats supported to change at run time.

As noted in the UIImage Class Reference, JPEG files sometimes have the extension .jpeg. If you're manually looking for JPEGs, you should check for both .jpg and .jpeg.

Testing for JPEGs only

NSString *extension = [selectedFile pathExtension];
BOOL isJpegImage = 
    (([extension caseInsensitiveCompare:@"jpg"] == NSOrderedSame) || 
     ([extension caseInsensitiveCompare:@"jpeg"] == NSOrderedSame));

if (isJpegImage)
{
    // Do image things here.
}

Testing for everything UIImage can load

NSString *loweredExtension = [[selectedFile pathExtension] lowercaseString];
// Valid extensions may change.  Check the UIImage class reference for the most up to date list.
NSSet *validImageExtensions = [NSSet setWithObjects:@"tif", @"tiff", @"jpg", @"jpeg", @"gif", @"png", @"bmp", @"bmpf", @"ico", @"cur", @"xbm", nil];
if ([validImageExtensions containsObject:loweredExtension])
{
    // Do image things here.
}

Testing for everything NSImage can load

NSString *loweredExtension = [[selectedFile pathExtension] lowercaseString];
NSSet *validImageExtensions = [NSSet setWithArray:[NSImage imageFileTypes]];
if ([validImageExtensions containsObject:loweredExtension])
{
    // Do image things here.
}

Problem

I would like to check if a string has a certain suffix, but would like to do a case insensitive checking. I'd need an alternative for this: ``` if ([selectedFile hasSuffix:@"jpg"] || [selectedFile hasSuffix:@"JPG"]) ``` or jPg, jpG, Jpg. Is there any short way to do this? I don't see how I could apply `caseInsensitiveCompare:` in this situation.

Original source