如何指定NSDictionary的keysOfEntriesPassingTest所需的块对象/谓词? [英] How do I specify the block object / predicate required by NSDictionary's keysOfEntriesPassingTest?

查看:346
本文介绍了如何指定NSDictionary的keysOfEntriesPassingTest所需的块对象/谓词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于学习(不是实际的)目的,我想使用下面的方法NSDictionary给我回来一组键使用我已经定义的测试值。不幸的是不知道如何指定谓词。

For learning (not practical -- yet) purposes, I'd like to use the following method on an NSDictionary to give me back a set of keys that have values using a test I've defined. Unfortunately have no idea how to specify the predicate.

NSDictionary keysOfEntriesPassingTest:
- (NSSet *)keysOfEntriesPassingTest:(BOOL (^)(id key, id obj, BOOL *stop))predicate

我的值是NSURLs,我想回到所有的端口8080的URL。这里是我的编码,虽然它真的没有意义,我认为是正确的:

Let's say for example all my values are NSURLs, and I'd like to get back all the URLs that are on port 8080. Here's my stab at coding that -- though it doesn't really make sense to me that it'd be correct:

NSSet * mySet = [myDict keysOfEntriesPassingTest:^(id key, id obj, BOOL *stop) {
                 if( [[obj port] isEqual: [NSNumber numberWithInt: 8080]]) {
                     return key;
                 }]

这是因为我得到了以下编译器错误:

And that's because I get back the following compiler error:


不兼容的块指针类型初始化'void(^)(struct objc_object *,struct objc_object *,BOOL *)',expected'BOOL objc_object *,struct objc_object *,BOOL *)'

incompatible block pointer types initializing 'void (^)(struct objc_object *, struct objc_object *, BOOL *)', expected 'BOOL (^)(struct objc_object *, struct objc_object *, BOOL *)'

我缺少什么?我会欣赏一个指针,在一些文档,更详细的关于块对象的谓词应该是。

谢谢!

What am I missing? I'd appreciate a pointer at some docs that go into more detail about the "Block object" that the predicate is supposed to be.
Thanks!

这是代码工作原理:

NSSet *mySet = [myDict keysOfEntriesPassingTest:^(id key, id obj, BOOL *stop)
{
  if ([[obj port] isEqual:[NSNumber numberWithInt: 8080]])
     return YES;
   else
     return NO;
}];


推荐答案

错误表示您的块必须返回 BOOL ,而不是 id 。检查文档。如果键/ obj对通过所需的测试,我怀疑你会返回 YES

The error indicates that your block must return a BOOL, rather than id. Check the docs. I suspect you are expected to return YES if the key/obj pair passes the desired test.

这篇关于如何指定NSDictionary的keysOfEntriesPassingTest所需的块对象/谓词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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