将方法选择器添加到字典中 [英] Add method selector into a dictionary

查看:113
本文介绍了将方法选择器添加到字典中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在字典中添加一个选择器(主要目的是在完成某些操作后识别回调方法和委托)

I want to add a selector into a dictionary (the main purpose is for identifying the callback method and delegate after finish doing something)

但我发现我可以不这样做,程序将收到错误EXC_BAD_ACCESS。
有没有其他方法可以将该方法选择器添加到字典中?
感谢您的帮助。

But I find that I can not do that, the program will get an error "EXC_BAD_ACCESS". Are there any other way for me to add that method selector to a dictionary? Thanks for your help.

推荐答案

向字典添加新条目有两件事(除了添加它之外)到字典,显然):

Adding a new entry to a dictionary does two things (in addition to adding it to the dictionary, obviously):


  1. 它需要一个键值的副本。这意味着密钥对象必须实现 NSCopying 协议

  2. retain 价值。这意味着它需要实现 NSObject 协议

  1. It takes a copy of the key value. This means that the the key object must implement the NSCopying protocol
  2. retains the value. This means that it needs to implement the NSObject protocol

这可能是第二次这导致你的 EXC_BAD_ACCESS

It's probably the second that's causing your EXC_BAD_ACCESS.

至少有两种解决方法。

首先,您可以将实现选择器的类的实例添加到字典中,而不是添加选择器。通常你的类将继承自 NSObject ,它会正常工作。请注意,它将保留该类,但可能不是您想要的。

Firstly, rather than adding the selector you could add the instance of the class that implements the selector to your dictionary. Usually your class will inherit from NSObject and it will work fine. Note that it will retain the class though, maybe not what you want.

其次,您可以使用<$ c $将选择器转换为字符串(并再次返回) c> NSSelectorFromString 和 NSStringFromSelector docs在这里)。

Secondly, you can convert a selector to a string (and back again) using NSSelectorFromString and NSStringFromSelector (docs are here).

这篇关于将方法选择器添加到字典中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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