问题
How can I send a block and its argument to a method ? so the method receive the block and the block receives the argument and I run the block in the method iteslf...
回答1:
Just pass the block and its argument to the method as separate arguments. Then send #value:
to the block to pass the argument to the block. E.g.
methodTaking: aBlock and: anArgument
aBlock value: anArgument.
...
回答2:
For an example have a look at the sort:
method of OrderedCollection
(you'll find the block evaluated finally in SortedCollection>>mergeFirst:middle:last:into:by:
).
Inside a method that accepts a block as parameter, you would evaluate the block, this means call it with parameters and use the result. Not so much try to "access the argument of the block".
You would e.g. send a message with a block as parameter to a collection of colors to sort it by luminance:
colors := OrderedCollection new.
colors addAll: { Color red. Color yellow. Color white. Color black }.
colors sort: [:c1 :c2 | c1 luminance <= c2 luminance].
results in: "an OrderedCollection(Color black Color red Color yellow Color white)"
来源:https://stackoverflow.com/questions/26889234/method-that-accepts-a-block-and-the-block-accepts-an-argument