以 UIButton* 为键的 NSMutableDictionary - iPhone 开发 [英] NSMutableDictionary with UIButton* as keys - iPhone development

查看:53
本文介绍了以 UIButton* 为键的 NSMutableDictionary - iPhone 开发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 iPhone 开发的新手,我有一个问题可能有一个非常简单的答案.我正在尝试向视图添加按钮,这些按钮与我定义的自定义类相关联.当我将按钮添加到视图时,我想知道这些按钮对应的类.这是因为当我按下按钮时,我需要获取一些关于类的信息,但是消息的接收者是另一个类.我在网上找不到有关错误的信息.我遇到的问题是我正在尝试创建一个 NSMutableDictionary,其中键的类型为 UIButton*,值是我的自定义类型:

I'm new to iPhone development and I have a question that may have a very simple answer. I am trying to add buttons to a view and these buttons are associated with a custom class that I defined. When I add the buttons to the view, I would like to know what class these buttons correspond to. This is because when I press the button, I need to get some information about the class, but the receiver of the message is another class. I couldn't find information about an error that I'm getting on the web. The problem I have is that I'm trying to create an NSMutableDictionary where the keys are of type UIButton* and the values are of my custom type:

   // create button for unit
   UIButton* unitButton = [[UIButton alloc] init];
   [sourceButtonMap setObject:composite forKey:unitButton];

当然,sourceButtonMap在类中定义并在init函数中初始化为sourceButtonMap = [[NSMutableDictionary alloc] init];

Of course, the sourceButtonMap is defined in the class and initialized in the init function as sourceButtonMap = [[NSMutableDictionary alloc] init];

尝试添加键值对时出现的错误是:

The error I get when I try to add the key-value pair is:

*** 由于未捕获的异常NSInvalidArgumentException"而终止应用程序,原因:*** -[UIButton copyWithZone:]:无法识别的选择器发送到实例 0x3931e90'

这是因为我无法将 UIButton* 存储为键吗?谁能指出我为什么会收到此错误?谢谢大家,

Is this happening because I can't store UIButton* as keys? Can anyone point me why I'm getting this error? Thank you all,

推荐答案

我发现的一种方法是使用构造一个 NSValue 作为键.要创建该使用:

One way I found was to use construct an NSValue to use as the key. To create the that use:

[NSValue valueWithNonretainedObject:myButton].

这里的警告似乎是,如果按钮被垃圾回收,键将持有无效引用.

The caveat here seems to be that if the button is garbage collected, the key will hold an invalid reference.

您可以在循环字典时再次获取对 UIButton 的引用,如下所示:

You can get the reference to the UIButton again while looping through the Dictionary like so:

for (NSValue* nsv in myDict) {
    UIButton* b = (UIButton*)[nsv nonretainedObjectValue];
    ...
}

这篇关于以 UIButton* 为键的 NSMutableDictionary - iPhone 开发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆