Why doesn't this rudimentary Objective C-block code work?

大憨熊 提交于 2019-12-12 21:41:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!