Let’s say I have an array containing Blocks, and I need to assert that all of them expect a given number of arguments.
Is there a way to find this out programmatically?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This is indeed possible, for any recent version of Clang.
The Apple ABI for Blocks is private but also published. Since that document tells us the layout the compiler will use for a Block object, we can duplicate that information in a header file and use it to access the components of a Block.
Mike Ash’s MABlockForwarding project does just that (see also the article) — much of the stuff at the top of this file is a copy-paste from the ABI doc. The thing that he created which we are interested in is the
BlockSig()function:which will return (for Blocks that have it (which they all do with recent Clang)), a type encoding string describing the Block’s return and argument types. From there, you can create an
NSMethodSignatureobject, and ask it for itsnumberOfArguments:The result there is 3, because it includes a hidden argument for the Block itself (and Blocks don’t use the hidden
_cmdargument or it would be 4).