self.dictionary即使充满键和值也会返回null



我正在Xcode上编写一个数独应用程序,对于游戏的每个单元,我都将一个标签和一个按钮配对,一个在另一个之上。当用户单击按钮时,标签上的数字将发生变化。我认为NSMutableDictionary可以方便地处理每个按钮/标签对,所以我创建了一个以按钮为键、以标签为值的字典。为了测试字典,我打印出了其中一个按钮的值,但结果为null。这是我的代码:

//Within my ViewController.h file
@property (weak, nonatomic) NSMutableDictionary *dictionary;
//Within my ViewController.m file
 self.dictionary = [NSMutableDictionary dictionary];
//the (id<NSCopying>)self.A1Button is for casting purposes
[self.dictionary setObject: self.A1Label forKey: (id<NSCopying>)self.A1Button];
[self.dictionary setObject: self.A2Label forKey: (id<NSCopying>)self.A2Button];
[self.dictionary setObject: self.A3Label forKey: (id<NSCopying>)self.A3Button];
[self.dictionary setObject: self.A4Label forKey: (id<NSCopying>)self.A4Button];
[self.dictionary setObject: self.A5Label forKey: (id<NSCopying>)self.A5Button];
[self.dictionary setObject: self.A6Label forKey: (id<NSCopying>)self.A6Button];
[self.dictionary setObject: self.A7Label forKey: (id<NSCopying>)self.A7Button];
[self.dictionary setObject: self.A9Label forKey: (id<NSCopying>)self.A9Button];
NSLog(@"%@", [self.dictionary objectForKey:self.A2Button]);

我得到的是:

2015-12-28 05:44:49.940 Sudoku[6349:292670] (null)

有人能解释一下发生了什么吗?谢谢

如果A1Button是UIButton,它不支持NSCopying协议。字典关键字需要支持它。

@property (weak, nonatomic) NSMutableDictionary *dictionary;

您必须将属性更改为strong,当然它会崩溃,因为方法copy没有在UIButton中实现,而目前它没有实现,因为self.dictionary使用weak赋值保持在nil
您应该重新审视您的逻辑,如果您真的想使用UIButton作为键,最好使用NSMapTable
点击此处了解更多信息。

明白了!我没有使用NSMutableDictionary,而是使用NSMapTable来存储键和值。对于这两种数据结构之间的差异,可以在这里找到一个很好的解释:

NSMapTable和NSMutableDictionary的差异

在我的ViewController.h文件中,我写了

@属性(强,非原子)NSMapTable*mapTable;

来声明我的NSMapTable。

然后,在我的ViewController.m文件中,我写了

self.mapTable = [NSMapTable mapTableWithKeyOptions:NSMapTableStrongMemory
                                             valueOptions:NSMapTableWeakMemory];
[self.mapTable setObject: self.A1Label forKey:self.A1Button];
[self.mapTable setObject: self.A2Label forKey:self.A2Button];
[self.mapTable setObject: self.A3Label forKey:self.A3Button];
[self.mapTable setObject: self.A4Label forKey:self.A4Button];
[self.mapTable setObject: self.A5Label forKey:self.A5Button];
[self.mapTable setObject: self.A6Label forKey:self.A6Button];
[self.mapTable setObject: self.A7Label forKey:self.A7Button];
[self.mapTable setObject: self.A8Label forKey:self.A8Button];
[self.mapTable setObject: self.A9Label forKey:self.A9Button];

您可以看到,使用NSMapTable,我可以指定我想要弱内存还是强内存。我的代码编译后没有任何错误。非常感谢!

最新更新