case insensitive checking of suffix of NSString case insensitive checking of suffix of NSString objective-c objective-c

case insensitive checking of suffix of NSString


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.}


[[selectedFile lowercaseString] hasSuffix:@"jpg"]


mipadi's suggestion is best, but since you mentioned caseInsensitiveCompare:, this is how you would use that:

BOOL hasSuffix = (NSOrderedSame == [[selectedFile substringFromIndex:[selectedFile length] - 3]] caseInsensitiveCompare:@"JPG"]);

That's a mouthful!

You could also use rangeOfString:options:, passing your suffix and NSCaseInsensitiveSearch.