ios - self.dictionary 返回 null,即使它充满了键和值

标签 ios objective-c dictionary

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

//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 协议(protocol)。需要字典键来支持它。

@property (weak, nonatomic) NSMutableDictionary *dictionary;

您必须将属性更改为 strong,当然它会崩溃,因为 copy 方法目前未在 UIButton 中实现这不是因为 self.dictionary 使用 weak 赋值保持设置为 nil
您应该重新审视您的逻辑,如果您真的想使用 UIButton 作为键,最好使用 NSMapTable
更多信息 here .

关于ios - self.dictionary 返回 null,即使它充满了键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34494646/

相关文章:

ios - IOS Swift 中的容器 View 中未触发按钮操作

objective-c - 获取屏幕上某种颜色占据的区域 - iOS

java - Mac 的 SetParent 函数(Java、AppleScript 或 Objective-C)

python - 如何按多个键对对象进行排序?

python - 在 Python 中合并字典的层次结构

ios - 如何在 iOS Swift 中实时录制音频声音,然后使用内置扬声器或耳机播放?

ios - 如何从TextField中获取十进制值并在Objective C中进行计算

如果在 JS 中初始化,iOS JSON Store 打开失败

ios - Objective C 文本字段格式化程序逗号每两个数字

c++ - map::find 具有可比较但不可转换为 key_type 的类型