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.
If
selectedFileis 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
NSStringhas many methods for working with paths, includingpathExtension.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
UIImageare listed in the UIImage Class Reference, along with their extensions.If you’re writing for Mac OS,
NSImagehas a class method calledimageFileTypes, 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
Testing for everything UIImage can load
Testing for everything NSImage can load