我正在 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/