一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

iOS自定义NSDictionary的Key的例子

时间:2022-06-25 23:35:25 编辑:袖梨 来源:一聚教程网

提出问题:

1.为什么需要自定义NSDictionary的Key?
2.系统对自定义的Key有什么要求?

答:

1.我遇到的实际问题是一个三级菜单,每一级都需要记录是否被选中。我选择用三个小的tableView来实现这个功能,但是我又要去想什么样的数据才能适应这个界面,然后我就想到了用个很大的字典来存储信息;
2.首先要实现NSCopying协议里的copyWithZone,然后要重写NSObject中的isEqual方法。

代码如下:

//.h
 
#import
 
//需要在.h文件里就遵守协议,不然会检测不到是否遵守NSCopying
@interface AreaModel : NSObject
 
//一些用于记录信息的字符串属性
@property (nonatomic,copy) NSString *areaString;
@property (nonatomic,copy) NSString *areaIDString;
//记录是否选中的属性
@property (nonatomic,assign) BOOL isSelected;
 
@end
 
//.m
 
#import "AreaModel.h"
 
@interface AreaModel()
//用于判断两个对象是否是同一对象的属性
@property (nonatomic,assign) NSUInteger myHash;
@end
 
@implementation AreaModel
 
#pragma mark --
- (id)copyWithZone:(nullable NSZone *)zone
{
    AreaModel *areaModel = [[[self class] allocWithZone:zone] init];
    
    //对象使用copyWithZone
    areaModel.areaString = [self.areaString copyWithZone:zone];
    areaModel.areaIDString = [self.areaIDString copyWithZone:zone];
    //基础数据类型则简单赋值
    areaModel.isSelected = self.isSelected;
    areaModel.myHash = self.myHash;
    
    return areaModel;
}
 
- (id)init
{
    self = [super init];
    if (self) {
    //初始化的时候给myHash赋值,值为根据内存地址转为的无符号长整型
        _myHash = (NSUInteger)self;
    }
    return self;
}
 
//有可能非必要重写get方法
- (NSUInteger)hash
{
    return _myHash;
}
 
//重写isEqual
- (BOOL)isEqual:(id)object
{
    return self.myHash == ((AreaModel *)object).myHash;
}
 
//为了便于阅读,所以
#pragma mark -- 重写description方法
- (NSString *)description
{
    return [NSString stringWithFormat:@"<%@: %p; area = %@; areaID = %@; isSelected = %@>",self.class,self,self.areaString,self.areaIDString,self.isSelected?@"YES":@"NO"];
}
 
@end

最终用到的数据:

AreaModel *pModel1 = [AreaModel new];
pModel1.areaString = @"安徽省";
pModel1.areaIDString = @"01";
 
AreaModel *pModel2 = [AreaModel new];
pModel2.areaString = @"海南省";
pModel2.areaIDString = @"02";
 
AreaModel *cModel1 = [AreaModel new];
cModel1.areaString = @"合肥市";
cModel1.areaIDString = @"0101";
 
AreaModel *cModel2 = [AreaModel new];
cModel2.areaString = @"芜湖市";
cModel2.areaIDString = @"0102";
 
AreaModel *aModel1 = [AreaModel new];
aModel1.areaString = @"弋江区";
aModel1.areaIDString = @"010201";
aModel1.isSelected = YES;
NSDictionary *dictionary = @{
                             pModel1 : @{
                                     cModel1 : @[],
                                     cModel2 : @[aModel1]
                                     },
                             pModel2 : @{}
                             };

热门栏目