开发者

Apply a block to all objects of an NSArray

Is there a way to apply a block to all the objects of an array?

Let's say I have an amazing block:

void (^myAmazingBlock)(NSNumber *) = ^(NSNumber *aFooNumber) {
    NSLog(@"Log message from an Amazing Block: %@", aFooNumber);
};

To apply my block to all the objects of my array, this works:

for (NSNumber *aNumber in myArray) {
    myAmazingBlock(aNumber);
}

Is it possible to get rid of the fast enumeration loop, and have something similar in the spirit to:

[myArray valueForKeyPath:@"@distinctUnionOfObjects.^myAmazingBlock"]; // This code doesn't work. It's just to show the style of what I'm trying to write.

I don't have any specific use in mind ; I was just being curious of the other possible wa开发者_如何学Cys to write this.


Edit:

It's possible to use enumerateObjectsUsingBlock: (Thank you paulbailey).

You then have to declare your block like this:

void (^myAmazingBlock2)(id, NSUInteger, BOOL *) = ^(id aFooNumber, NSUInteger idx, BOOL *stop) {
    NSLog(@"Amazing BLOCK 2 %@", aFooNumber);
};

[myArray enumerateObjectsUsingBlock:myAmazingBlock2];

Unfortunately, the fast enumeration loop is still the most readable solution.


You could use enumerateObjectsUsingBlock: perhaps? Obviously you'd have to adapt the parameters of your block to match those specified.

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜