Ask a question:
1. Why do I need to customize Nsdictionary key?
2. What is the system requirement for a custom key?
For:
1. The real problem I encountered was a level three menu, each of which required records to be selected. I chose to use three small tableview to achieve this function, but I have to think about what kind of data to adapt to the interface, and then I think of a large dictionary to store information;
2. First implement the Copywithzone in the Nscopying protocol, and then rewrite the IsEqual method in NSObject.
The code is as follows:
. h
#import <Foundation/Foundation.h>
You need to comply with the agreement in the. h file, or you will not be able to detect compliance with nscopying
@interface areamodel:nsobject<nscopying>
Some string properties for logging information
@property (nonatomic,copy) NSString *areastring;
@property (nonatomic,copy) NSString *areaidstring;
Record whether the selected property
@property (nonatomic,assign) BOOL isselected;
@end
. m
#import "AreaModel.h"
@interface Areamodel ()
property to determine whether two objects are the same object
@property (nonatomic,assign) Nsuinteger Myhash;
@end
@implementation Areamodel
#pragma mark--<NSCopying>
-(ID) Copywithzone: (Nullable Nszone *) zone
{
Areamodel *areamodel = [[self class] allocwithzone:zone] init];
Object using Copywithzone
areamodel.areastring = [self.areastring copywithzone:zone];
areamodel.areaidstring = [self.areaidstring copywithzone:zone];
The underlying data type is simply assigned
areamodel.isselected = self.isselected;
Areamodel.myhash = Self.myhash;
return Areamodel;
}
-(ID) init
{
self = [super init];
if (self) {
When initialized, the value is assigned to the Myhash, which is the unsigned long integer converted to the memory address.
_myhash = (nsuinteger) self;
}
return self;
}
It may not be necessary to rewrite the Get method
-(Nsuinteger) hash
{
return _myhash;
}
Rewrite isequal
-(BOOL) IsEqual: (ID) object
{
return Self.myhash = = ((Areamodel *) object). Myhash;
}
In order to facilitate reading, so
#pragma mark--Rewrite the description method
-(NSString *) description
{
return [NSString stringwithformat:@ "<%@:%p; area =%@; areaid =%@; isselected =%@>", Self.class,self,self.areastri ng,self.areaidstring,self.isselected?@ "YES": @ "NO"];
}
@end
Data to be used in the end:
Areamodel *pmodel1 = [Areamodel new];
pmodel1.areastring = @ "Anhui province";
pmodel1.areaidstring = @ "01";
Areamodel *pmodel2 = [Areamodel new];
pmodel2.areastring = @ "Hainan Province";
pmodel2.areaidstring = @ "02";
Areamodel *cmodel1 = [Areamodel new];
cmodel1.areastring = @ "Hefei";
cmodel1.areaidstring = @ "0101";
Areamodel *cmodel2 = [Areamodel new];
cmodel2.areastring = @ "Wuhu";
cmodel2.areaidstring = @ "0102";
Areamodel *amodel1 = [Areamodel new];
amodel1.areastring = @ "Yijiang area";
amodel1.areaidstring = @ "010201";
amodel1.isselected = YES;
Nsdictionary *dictionary = @{
PModel1: @{
CModel1: @[],
CModel2: @[amodel1]
},
PModel2: @{}
};