将块应用于 NSArray 的所有对象
有没有办法将块应用于数组的所有对象?
假设我有一个令人惊叹的块:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您也许可以使用
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