I would like to save an objective-c block to a file (or any other storage e.g. FTP server) and later load it from there and execute it.
From the Blocks Programming Guide > Using Blocks > Copying Blocks, I know that blocks can be stored in the heap. Because anything stored there can be modified, I think that it is possible to read and write arbitrary content from/to the heap and treat the data as a block.
My problem is, how do you save a block to a file? I don't even know what its structure is/how many bytes it covers. I highly doubt that doing a sizeof() and then reading/writing as many bytes is sufficient. Please help me in finding a start to read and write blocks to/from memory and to understand how they are composed.
Let's start from this code:
void (^myBlock)(void) = ^{ printf("Hello, I'm a Block\n"); };
printf("block size: %lu\n", sizeof(myBlock));
myBlock();
Output:
block size: 4
Hello, I'm a Block
As you can imagine, if this works, a long list of fascinating concepts could be implemented in iOS. Just to name a few:
It is not possible: when you copy the block on the heap you are copying the address of the block itself, not the code of the block. Moreover the possibility of run not compiled and signed code is against the concept of sandbox, and it'd open the possibility to run evil code in your app breaking the security. You could implement a custom language interpreter in your app to run a interpred code, but it would be against the Apple policy and it would be rejected during the review process.