在Objective-C中复制块(即:将它们复制到实例变量) [英] Copying blocks (ie: copying them to instance variables) in Objective-C

查看:104
本文介绍了在Objective-C中复制块(即:将它们复制到实例变量)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解块。我得到如何正常使用它们,当直接传递给一个方法。我现在感兴趣的是取一个块,将它(说)存储在一个实例变量中并稍后调用它。



块编程指南使它听起来像我可以做这通过使用Block_copy / retain来复制块,但是当我尝试运行它我崩溃我的程序。

  (void)setStoredBlock 
{
int salt = 42;
m_storedBlock = ^(int incoming){return 2 + incoming + salt; };
[m_storedBlock retain];
}

我尝试稍后调用它:

   - (void)runStoredBlock 
{
int outputValue = m_storedBlock(5);
NSLog(@当我们运行我们存储的blockwe回来:%d,outputValue);
[m_storedBlock release];
}

任何人都有什么见解?



非常感谢!

$ b {
int salt = 42;
m_storedBlock = Block_copy(^(int incoming){return 2 + incoming + salt;});
}


I'm trying to understand blocks. I get how to use them normally, when passed directly to a method. I'm interested now in taking a block, storing it (say) in an instance variable and calling it later.

The blocks programming guide makes it sound like I can do this, by using Block_copy / retain to copy the block away, but when I try to run it I crash my program.

- (void) setupStoredBlock
{
    int salt = 42;
    m_storedBlock = ^(int incoming){ return 2 + incoming + salt; };
    [m_storedBlock retain];
}

I try to call it later:

- (void) runStoredBlock
{
    int outputValue = m_storedBlock(5);
    NSLog(@"When we ran our stored blockwe got back: %d", outputValue);
    [m_storedBlock release];
}

Anyone have any insights? (Or, is there something I'm not getting with blocks?)

Thank you very much!

解决方案

You'll want to do this instead:

- (void) setupStoredBlock
{
    int salt = 42;
    m_storedBlock = Block_copy(^(int incoming){ return 2 + incoming + salt; });
}

这篇关于在Objective-C中复制块(即:将它们复制到实例变量)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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