Example of NSSet's objectsPassingTest function please?
Asked Answered
E

2

15

I'm going nuts here. For some reason I can't find a single, complete example of how to use the objectsPassingTest: function of NSSet (cocoa). Before anyone points me to the pages about blocks, I've seen those. The example given only shows how to declare the function, not the block that operates it, and when I tried their example with my own code it didn't work. I just want to see a couple of working examples of how the function might be used, then I'll be able to work it out for myself.

Etymologize answered 1/3, 2011 at 8:32 Comment(0)
B
30

Here is a quick example. Hope it helps.

    NSSet *set = [NSSet setWithObjects:@"1",@"2",@"3",@"4",@"5",nil];

    NSLog(@"%@",set); // Output (3,1,4,2,5) ... all objects

    NSSet *o = [set objectsPassingTest:^(id obj,BOOL *stop){
        NSString *so = (NSString *)obj;
        int intval = [so intValue];
        // accept objects less or equal to two
        BOOL r = (intval <= 2);
        return r;
    }];

    NSLog(@"%@",o); // Output (1,2) only objects smaller or equal  to 2
Briton answered 1/3, 2011 at 8:43 Comment(1)
Thanks, that should help immensely. I tried it out 'as is' earlier while at work, now about to try and adapt it to my own code. The weird thing is, I'm certain I tried this method but with more use of nested functions and dot syntax, so maybe that's where my problem was.Etymologize
T
4

I never used blocks. But I guess this is how it works.

NSSet *set = [NSSet setWithObjects:@"FooBar", @"Foo", @"Bar", @"Baz", nil];

NSSet *fooSet = [set objectsPassingTest:^(id obj, BOOL *stop) {
    BOOL testResult = NO;
    NSString *objStr = (NSString *)obj;
    if ([objStr hasPrefix:@"Foo"]) {
        testResult = YES;
    }
    if ([objStr hasSuffix:@"Bar"]) {
        testResult = YES;
    }
    return testResult;
}];

This will create a set with @"FooBar", @"Foo" and @"Bar", because only those pass the test (ie return YES).

Tolbooth answered 1/3, 2011 at 8:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.