在Objective-C中复制块(即:将它们复制到实例变量) [英] Copying blocks (ie: copying them to instance variables) in 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屋!