【发布时间】:2017-09-07 21:13:08
【问题描述】:
收到NSString 后,我想调用一个特定的代码块。我认为NSDictionary 最适合关联这些。简而言之,我正在使用类似的东西:
MyProtocol.h:
@protocol MyProtocol <NSObject>
typedef void (^Handler)(id<MyProtocol> obj, id data);
@end
MyClass.h:
@interface MyClass : NSObject <MyProtocol>
- (void)aMethodWithString:(NSString *)string andData:(id)data;
@end
MyClass.m:
@interface MyClass ()
void myCommandHandler(id<MyProtocol> obj, id data); // matches signature defined in protocol
@end
@implementation MyClass
void myCommandHandler(id<MyProtocol> obj, id data)
{
// ...
}
- (void)aMethodWithString:(NSString *)string andData:(id)data
{
static NSDictionary<NSString *, Handler> *handler;
static dispatch_once_t onceToken;
// don't allocate this dictionary every time the function is called
dispatch_once(&onceToken,
^{
handler =
@{
@"MyCommand":myCommandHandler,
};
});
// ... error checking, blah blah ...
Handler block;
if ((block = handler[string]))
{ block(self, data); }
}
@end
使用这个,我在字典文字构造中得到一个错误:
'void (__strong id
, __strong id)' 类型的集合元素不是 Objective-C 对象`
那么如何在字典中包含 C 函数或块引用?将有很多更大的复杂函数需要定义,因此非常最好不要将所有这些函数都定义在字典文字本身中(我知道这种技术会起作用)。 p>
--
另外,我不确定这里认为什么是正确的样式:(1)我最初在文件范围内的任何方法主体之外都有字典声明(没有dispatch_once(...)),它会产生相同的错误,但我认为也许通过(2)将它包含在使用该字典的唯一方法中,其他人会更容易看到发生了什么。出于某种原因,一种风格是否优于另一种风格?
【问题讨论】:
标签: ios objective-c function dictionary objective-c-blocks