Member-only story
Comparing Images iOS
1 min readOct 6, 2020
The isEqual: method is the only reliable way to determine whether two images contain the same image data. The image objects you create may be different from each other, even when you initialize them with the same cached image data. The only way to determine their equality is to use the isEqual: method, which compares the actual image data. Listing 1 illustrates the correct and incorrect ways to compare images.
Source: Apple Documentation
Swift
// Load the same image twice.let image1 = UIImage(named: "MyImage")
let image2 = UIImage(named: "MyImage")// The image objects may be different, but the contents are still equalif let image1 = image1, image1.isEqual(image2) {
// Correct. This technique compares the image data correctly.}if image1 == image2 {
// Incorrect! Direct object comparisons may not work.}
Objective-C
// Load the same image twice.UIImage* image1 = [UIImage imageNamed:@"MyImage"];
UIImage* image2 = [UIImage imageNamed:@"MyImage"];// The image objects may be different, but the contents are still equalif ([image1 isEqual:image2]) {
// Correct. This technique compares the image data correctly.}
if (image1 == image2) {// Incorrect! Direct object comparisons may not work.}