Using OC to customize a Intpair class as the key value of the Nsdictionary class, similar to the way Pair<int,int> used in Java, however, there are various problems encountered during the use, it is necessary to record.
first, the nscoping protocol needs to be implemented , and if not implemented, a warning is reported when using Intpair as key to add data to the dictionary: sending ' intpair *__strong to parameter of Incompatible type ' id<nscopying> _nonnull '
At first, the results run, and the SetObject Forkey function crashes directly here, and the SetObject Forkey statements are as follows:
So this method should be implemented.
Then, the implementation of the Nscopying protocol, found that the key value can not be compared for equality, the same key value has been added several times, through the search know, but also need to overload the NSObject two methods :
-(BOOL) IsEqual: (ID) object;-(nsuinteger) hash;
IsEqual method is a good understanding, used to determine whether two objects are equal, better implementation,
Hash method is necessary to explain, this method returns an integer value as the table address of the table, familiar with the HA sparse algorithm should understand that the same key value of the hash return value should also be the same
The following is the complete implementation of the Intpair class:
IntPair.h
#import <Foundation/Foundation.h> @interface intpair:nsobject<nscoding,nscopying> @property (nonatomic, assign) int first, @property (nonatomic,assign) int second;-(Intpair *) Initwithfirst: (int) First andsecond: (int) second; @end
Intpair.m
#import "IntPair.h" @implementation intpair-(Intpair *) Initwithfirst: (int) First andsecond: (int) second{Self.first = fi Rst Self.second = second; return self;} -(BOOL) IsEqual: (ID) object{Intpair *pair = (Intpair *) object; if (pair! = nil) {if (Self.first = = Pair.first && Self.second = = Pair.second) {return YES; }} return NO; -(Nsuinteger) hash{return self.first * + Self.second;} -(void) Encodewithcoder: (Nscoder *) acoder{nsnumber *first = [[NSNumber alloc] initWithInt:self.first]; NSNumber *second = [[NSNumber alloc] initWithInt:self.second]; [Acoder encodeobject:first forkey:@ "first"]; [Acoder encodeobject:second forkey:@ "Second"];} -(ID) Initwithcoder: (Nscoder *) adecoder{nsnumber *first = [Adecoder decodeobjectforkey:@ "first"]; NSNumber *second = [Adecoder decodeobjectforkey:@ "second"]; Self.first = [First intvalue]; Self.second = [Second intvalue]; return self;} -(ID) Copywithzone: (Nszone *) Zone{Intpair *pair = [[Intpair Allocwithzone:zone] InitWithFirst:self.first AndSecond:self.second]; return pair;} @end
iOS Custom Nsdictionary key value class