提出問題:
1.為什麼需要自定義NSDictionary的Key?
2.系統對自定義的Key有什麼要求?
答:
1.我遇到的實際問題是一個三級菜單,每一級都需要記錄是否被選中。我選擇用三個小的tableView來實現這個功能,但是我又要去想什麼樣的數據才能適應這個界面,然後我就想到了用個很大的字典來存儲信息;
2.首先要實現NSCopying協議裡的copyWithZone,然後要重寫NSObject中的isEqual方法。
代碼如下:
//.h
#import <Foundation/Foundation.h>
//需要在.h文件裡就遵守協議,不然會檢測不到是否遵守NSCopying
@interface AreaModel : NSObject<NSCopying>
//一些用於記錄信息的字符串屬性
@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 -- <NSCopying>
- (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 : @{}
};