这个基本的Objective C块代码为什么不起作用? [英] Why doesn't this rudimentary Objective C-block code work?

查看:75
本文介绍了这个基本的Objective C块代码为什么不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解积木的基本原理.我写了这个简单的测试:

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);

我希望控制台输出为"this block worked!",但是相反,我得到了大量错误号等,其结尾为:

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

怎么了?

建议使用以下答案

NSLog (@"%@", print_block());

但这也不起作用.该程序在块定义的开始处终止,控制台只说(lldb)和Xcode在块定义上放一个绿色箭头.箭头显示为:

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>

推荐答案

Vatev的评论正确.当您写时:

Vatev's comment is right on. When you write:

NSLog(@"%@", print_block);

您要在日志语句中将块print_block作为格式字符串的参数传递.您正在尝试打印块.这可能导致[print_block description]被调用.我不知道代码块是否实现-description方法,但是如果不实现,则会出现无法识别的选择器异常.

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());

这篇关于这个基本的Objective C块代码为什么不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆