How to specify a block object / predicate required by NSDictionaryOfEntriesPassingTest keys?

For training (but not practical) purposes, I would like to use the following method in NSDictionary to return to me a set of keys that have values ​​using the test I defined. Unfortunately, I don’t know how to specify a predicate.

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

Say, for example, all my values ​​are NSURL, and I would like to return all the URLs that are on port 8080. Here's my hit on coding, although it doesn't seem to me any sense that it's' d Correct:

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

And this is because I am returning the following compiler error:

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

What am I missing? I would be grateful for a pointer to some documents that describe in more detail about the "block object", which is supposed to be a predicate .
Thank!




And this is the code that works:

 NSSet *mySet = [myDict keysOfEntriesPassingTest:^(id key, id obj, BOOL *stop) { if ([[obj port] isEqual:[NSNumber numberWithInt: 8080]]) return YES; else return NO; }]; 
+4
cocoa grand-central-dispatch macos
Jun 13 '10 at 23:11
source share
2 answers

The error indicates that your block should return BOOL , not id . Check documents. I suspect that you expect to return YES if the key / obj pair performs the required test.

+3
Jun 13 '10 at 23:15
source share

A small extension to Barry's answer ....

A block is like a function pointer with one key difference. The block will output the return type from the return statements contained inside, or it will give an error message similar to the one you said (LLVM compiler error should be a little more reasonable).

When you wrote:

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

Consider as a function:

 BOOL bob(id key, id obj) { if( [[obj port] isEqual: [NSNumber numberWithInt: 8080]]) { return key; } } 

See the problem? There is a code path that does not return a value, and thus the compiler will complain.

+7
Jun 14 '10 at 4:40
source share



All Articles