To start with the requirements, the client needs to count the number of clicks on an event, and there is a data type

 [{"id":"1"."readings":"2"}, {"id":"2"."readings":"1"}]
Copy the code

If you click a button, such as a button with id == 1, you need to set the

{"id":"1"."readings":"2"} 
Copy the code

Add 1 to the readings in this number, and the result is 1

 [{"id":"1"."readings":"3"}, {"id":"2"."readings":"1"}]
Copy the code

Just upload this data to the server,

Thinking 🤔

I saw my former colleague’s implementation go through a series of traversals to see if ids are equal, given that arrays have

- (BOOL)containsObject:(ObjectType)anObject;
Copy the code

This method, can directly use this method to achieve. We know that containsObject is a method that compares pointer addresses, so using it directly is definitely not going to work

Implement 😉

Create a custom class to override

- (BOOL)isEqual:(id)other
- (NSUInteger)hash
Copy the code

interface

@interface Zhai : NSObject
@property (nonatomic.strong) NSString *id;
@property(nonatomic.assign) NSInteger readings;
@end
Copy the code

implementation

@implementation Zhai

- (BOOL)isEqual:(id)other
{
    if (other == self) {
        return YES;
    } else {
        return [self isEqualZhai:other];
    }
}

-(BOOL)isEqualZhai:(Zhai *)objc{
    if(! objc) {return false;
    }
    BOOL isEqual = (self.id && objc.id) && [self.id isEqualToString:objc.id];
    return isEqual;
    
}

// Do not implement this method for arrays only, nssets and dictionaries do
- (NSUInteger)hash
{
    NSUInteger hashValue = [super hash];
    return hashValue;
}

@end
Copy the code

Verify 😺

Let’s start by creating three variables

Zhai *zhai = [Zhai new];
zhai.id = @ "1";
zhai.readings = 1;

Zhai *zhai2 = [Zhai new];
zhai2.id = @ "2";
zhai2.readings = 3;

Zhai *zhai3 = [Zhai new];
zhai3.id = @ "2";
zhai3.readings = 1;

BOOL isEqual = [zhai2 isEqual:zhai3];
Copy the code

Here isEqual prints YES, success

Declare one more variable

NSMutableArray *arr = @[zhai,zhai2].mutableCopy;
// Print YES
NSLog(@"%d",isEqual);

Zhai *zhai4 = [Zhai new];
zhai4.id = @ "2";
zhai4.readings = 1;

BOOL contain = [arr containsObject:zhai4];
// contain YES
NSLog(@"contain %d",contain);
if (contain) {
   // We can see that the implementation of indexOfObject is related to the isEqual method
    NSInteger index = [arr indexOfObject:zhai4];
    Zhai * zhai5 =  arr[index];
  	// Increase the number of clicks by 1
    zhai5.readings += 1;
}
Copy the code

Conclusion 📓

This implements custom class comparison and array inclusion methods.

The code is a little cleaner, reducing the list of traversals, but if the system’s containsObject: method is also traversal, it should be a lot more complicated. The above