将块应用于 NSArray 的所有对象

发布于 2024-10-20 10:27:29 字数 963 浏览 0 评论 0原文

有没有办法将块应用于数组的所有对象?

假设我有一个令人惊叹的块:

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

要将我的块应用到数组的所有对象,这是可行的:

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

是否可以摆脱快速枚举循环,并在精神上有类似的东西:

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

我没有任何具体用途要牢记;我只是好奇其他可能的写法。


编辑:

可以使用enumerateObjectsUsingBlock:(谢谢paulbailey)。
然后,您必须像这样声明您的块:

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

[myArray enumerateObjectsUsingBlock:myAmazingBlock2];

不幸的是,快速枚举循环仍然是最具可读性的解决方案。

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 ways 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

淡笑忘祈一世凡恋 2024-10-27 10:27:29

您也许可以使用 enumerateObjectsUsingBlock: ?显然,您必须调整块的参数以匹配指定的参数。

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文