问题
I am trying to understand the fundamentals of blocks. I wrote this simple test:
NSString *(^print_block) () = ^ (NSString *returned_string){
return @"this block worked!";
};
NSLog(@"%@", print_block);
I expected console output to be "this block worked!"
, but instead I get a big flood of error numbers and etc,, ending with:
terminate called throwing an exception
What up?
Edit: the answer has been suggested to use:
NSLog (@"%@", print_block());
But that doesn't work either. The program terminates at the start of the block definition, with the console saying only (lldb)
and Xcode putting a little green arrow at the block definition. The arrow reads:
Thread 1: EXC_BAD_ACCESS (code=1, address=0x5f646e71)
I've tried something else that doesn't work:
NSString *(^print_block) () = ^ (NSString *returned_string){
NSString *return_me = @"this block worked!";
return return_me;
};
NSLog(@"%@", print_block);
But at least this doesn't terminate the program. It runs fine. But the console output is still wrong:
<__NSGlobalBlock__: 0x5a58>
回答1:
Vatev's comment is right on. When you write:
NSLog(@"%@", print_block);
you're passing the block print_block
as the argument for the format string in the log statement. You're trying to print the block. This probably results in [print_block description]
being called. I don't know if blocks implement a -description
method, but if not then you'll get an unrecognized selector exception.
Also, the way you've declared the block is incorrect. You don't need to include the return value in the parameter list.
The following code works as you expect:
NSString *(^print_block)() = ^{
return @"this block worked!";
};
NSLog(@"%@", print_block());
来源:https://stackoverflow.com/questions/11691780/why-doesnt-this-rudimentary-objective-c-block-code-work